Why aliases in a non-interactive Bash shell do not work

BashAliasNon InteractiveShopt

Bash Problem Overview


I am trying to use aliases in a non-interactive bash shell. I have defined my aliases in ~/.bashrc and I have set the variable BASH_ENV=~/startUpFile. The contents of the startUpFile are source ~/.bashrc.

I can see that my aliases are recognized, when I execute the alias command. However, if I try to use an alias defined in ~/.bashrc, Bash can't recognized it. It gives me the unknown command error.

With the TCSH shell it is pretty easy to do this because the ~/.cshrc file is always read.

Any ideas how I can do this with a Bash shell?

Bash Solutions


Solution 1 - Bash

The command shopt -s expand_aliases will allow alias expansion in non-interactive shells.

Solution 2 - Bash

.bashrc is only processed by interactive shells.

In addition, aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt. Unless, of course, POSIX mode is invoked by calling the shell with the name sh instead of bash.

People who use aliases a lot often source their .bashrc at the end of their profile so that the aliases are there even for non-interactive shells. This might not be the best way, but it is pretty common.

It's things like this that lead me to believe that in the 21st century we should abandon shell scripts in favor of a full-blown language like Python. It's a lot more predictable.

Solution 3 - Bash

You have to

shopt -s expand_aliases

in the file pointed to in your BASH_ENV

Solution 4 - Bash

I had similar issue, in the end, I found out that ~/.bashrc was all I needed.

However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :

If not running interactively, don't do anything
[ -z "$PS1" ] && return

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnisahView Question on Stackoverflow
Solution 1 - BashJim LewisView Answer on Stackoverflow
Solution 2 - BashMichael DillonView Answer on Stackoverflow
Solution 3 - BashVinko VrsalovicView Answer on Stackoverflow
Solution 4 - BashtomaszbakView Answer on Stackoverflow