I have some work that requires I move around between various sub-directories. Thus, the easiest way I have found to do that is to use dired. I also have to view some files (plain text or code), so another benefit is I can just hit RET on the filename to do that. However, I sometimes need to run shell commands on these files. Before I used Emacs, I would just use Bash (navigating with pushd and popd, which is less convenient than dired), so this allowed me to run the commands I needed.

How can I easily combine the best of both methods? I see a couple options:

  1. Somehow keep a shell buffer in sync with the dired buffer. (Maybe somehow trigger pushd/popd/cd?)
  2. Set up some keyboard shortcuts for the shell buffer, to simulate movement and file viewing (the latter especially seems more difficult).
  3. Something else?

Note that I would prefer not to call shell-command (M-!) every time, because it is harder to execute multiple commands in quick succession, and interact with the command output, in addition to having a less-than-convenient default keybinding.


1 Answer 1


You can modify dired-after-readin-hook to send an appropriate command to your shell buffer. The following code creates a shell called dired-synced-shell if one doesn't already exist, and every time you change a directory in dired, runs a cd on the shell running in buffer dired-synced-shell.

(add-hook 'dired-after-readin-hook (lambda()
                     (unless (get-buffer "dired-synced-shell") (shell "dired-synced-shell"))
                     (process-send-string (get-buffer "dired-synced-shell") (format "cd %s\n" default-directory))
                     (message "Switched to new directory")))

OP Edit: Here are two issues I found, with workarounds:

  1. This doesn't work for switching to a dired buffer that already exists. Workaround: press g to refresh the buffer.

  2. This causes my shell prompt to get smashed together with the previous, as it might if the output of the previous command didn't contain a newline. (E.g. if my shell prompt is [scott@local]$, then on switching to a new dired buffer, I would see [scott@local]$ [scott@local]$. Workaround: add a newline to the beginning of my shell prompt.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.