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!
BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files. We can also incorporate BASH functions, variables, etc to make the Alias more programmatic and flexible.
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.
$2 is the second command-line argument passed to the shell script or function. Also, know as Positional parameters.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With