Emacs eshell launcher that changes to the working directory

Posted on Jan 16, 2025

When I open eshell from some buffer, I often want eshell to change directory [cd] to the buffer’s path. But, if eshell is already open it’ll just switch over, leaving the shell at whatever directory it was at.

Here’s a quick alternative interactive command that’ll do just that, i.e. cd to whatever directory the current buffer is at after switching to eshell 1:

(defun my-eshell-here ()
  "Open eshell in current buffer's directory."
  (interactive)
  (let ((dir (file-name-directory
              (or (buffer-file-name)
                  default-directory))))
    (eshell)
    (unless (string= dir default-directory)
      (eshell/cd dir)
        (eshell-send-input))))

I’ve added this to my Emacs config under the SPC o E binding.


  1. written with the help of Claude Sonnet 3.5 and karthink/gptel ↩︎