Skip to content

Use Bash Aliases from Emacs’s Minibuffer by Using Interactive Shell

Being able to execute a quick one-liner shell commands directly from Emacs
minibuffer is a real time saver. Emacs in general reduces needs to do things
from the terminal, but M-! which executes shell-command is really a gem. It
lets one execute a shell command by typing it in Emacs minibuffer.

It is not just that we don’t need to switch from Emacs to a terminal and back,
but it saves a lot of time by placing its output directly into an Emacs buffer,
ready to search, copy, replace or even execute some Elisp on the buffer. This
makes Emacs effectively an interactive terminal; sort of. However, shell
normally does not load user profile if it is not invoked as an interactive
shell, which makes aliases not available for use from Emacs’s minibuffer. By
default Emacs does not start shell processes in interactive mode.

To make M-!, it’s cousin M-&, async-shell-command, & Co, a bit more user
friendly, we can actually tell Emacs to invoke shell as an interactive shell by
passing “-ic” flags to the shell (yes both of them are needed). Emacs has a
variable for this, shell-command-switch:

(setq shell-command-switch “-ic”).

Now when we invoke shell-command or async-shell-command, Emacs will run them in
an interactive shell and we can use our aliases as if we are invoking shell from
a terminal.

There is one minor thing to take care of: by default Emacs will insert errors
received from shell in the output buffer. If this is not desired we can set
shell-command-default-error-buffer to some string which Emacs will use as a name
to error buffer for errors from the shell. For example when parsing the output
buffer with Elisp, it is actually nice to not have to take care of errors. So

(setq shell-command-default-error-buffer “Shell Command Errors”)

takes care of the error buffer for me.

Post a Comment

Your email is never published nor shared. Required fields are marked *