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