Why bash alias doesn’t work in scripts? [duplicate]

Your .bashrc is only used by interactive shells. https://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files says:

Invoked non-interactively

When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

but the value of the PATH variable is not used to search for the filename.

As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.

As you can see, there’s nothing about .bashrc there. Your alias simply doesn’t exist in the script.


But even if .bashrc were read, there’s another problem:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.

So if you wanted aliases to work in a script, you’d have to do shopt -s expand_aliases first. Or just use a shell function instead of an alias:

la() {
    ls -la
}

Leave a Comment