Commands from .bashrc not available in Emacs

I have some aliases and functions defined in ~/.bashrc.

I start emacs from a terminal window using emacs -nw

When I execute M-x shell-command, the aliases and functions from ~/.bashrc are not available, but give a “command not found”.

I’ve googled quite a bit but all the posts I come across say, if I understand them correctly, that ~/.bashrc is the place where this should work (rather than ~/.profile or ~/.bash_profile).

What am I missing?

Aliases are available only in interactive shell – a snapshot from bash man page:

Aliases are not expanded when the
shell is not interactive, unless the
expand_aliases shell option is set
using shopt
(see the description of shopt under SHELL BUILTIN COMMANDS below).

If you start Emacs from an interactive shell (in which .bashrc, etc. have executed), then the commands from your .bashrc should be available for both shell-command and shell, at least that’s how it works for me.

But yeah as the other answer says, there is not real way to get a .bashrc environment in emacs. There are some documentation about a .emacs_bash file, but that never worked for me.

Okay misread your question here. If you are looking for functions and aliases instead of commands by changing paths in .bashrc, the non-interactiveness is the problem. I guess you can change the default argument to shell-command (take a look at explicit-bash-args) to make bash interactive, but that probably has unintended consequences.

The accepted answer correctly states that “aliases are available only in interactive shell”.

This means that in order to load (rightly located indeed) aliases from ~/.bashrc, an interactive shell would have to be launched with Emacs‘s M-x shell-command (M-!).

To achieve this, add -i (interactive) switch to the M-x shell-command with:

(setq shell-command-switch "-ic")

Side Note, not Emacs related:
On some operating systems users would need to add the line source ~/.bashrc to ~/.bash_profile (or similar), since ~/.bashrc is not always auto-read by a system.

Leave a Comment