Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 639
nisah Avatar asked Oct 23 '09 21:10

nisah


People also ask

Do aliases work in bash scripts?

Bash Alias allows to aggregate multiple functions into a single command and also it avoids repetitive or large commands into a simple shortcut command.

How do aliases work bash?

A Bash alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding typing a long command sequence. If, for example, we include alias lm="ls -l | more" in the ~/. bashrc file, then each lm [1] typed at the command-line will automatically be replaced by a ls -l | more.

Which shells support aliases?

Please note that the alias command is built into a various shells including ksh, tcsh/csh, ash, bash and others.

What is the difference between an interactive shell and a non interactive shell?

An interactive shell reads commands from user input on a tty. Among other things, such a shell reads startup files on activation, displays a prompt, and enables job control by default. The user can interact with the shell. A shell running a script is always a non-interactive shell.


2 Answers

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

like image 75
Jim Lewis Avatar answered Sep 23 '22 04:09

Jim Lewis


.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.

like image 29
Michael Dillon Avatar answered Sep 24 '22 04:09

Michael Dillon