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

I'm using a Mac and I have this alias defined in .bashrc:

$cat .bashrc | grep la
alias la='ls -la'

then I try to use it in a script:

$cat ./mytest.sh  
#!/bin/bash
la

It runs and says it cannot find la:

./mytest.sh: line 2: la: command not found

Why is this? I tried on both Mac and Linux, same error!


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
}

The simplest answer is to fix this issue is to do the 2 important things in your script -or it wont' work, if you just do one thing.

#!/bin/bash -i

# Expand aliases defined in the shell ~/.bashrc
shopt -s expand_aliases

After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

If you don't do that, you'll get an error:

your_cool_alias: command not found