In linux, if I put a command in a script that contains an alias, I see that it doesn't get expanded. How can I fix that? I am using bash.
According the the TLDP page about aliases, you need to use the line shopt -s expand_aliases
in your code to expand aliases. The example below produced the expected output, but without the shopt line it just printed "my_ls: command not found":
#!/bin/bash
shopt -s expand_aliases
alias my_ls='ls -lrt'
echo "Trying my_ls"
my_ls
exit
If you want your shell aliases to be available in a script, you must manually include them. If they are defined in ~/.bashrc
, put a line
. ~/.bashrc
after the #!/bin/sh
line in your script. This will execute the contents of .bashrc in the context of your script.
Enabling posix mode (such as by calling bash as sh
or with the command (set -o posix) 2>/dev/null && set -o posix
should do the trick.
Even then, be aware that aliases are expanded as they are parsed, and the ordering between parsing and execution is poorly defined. For example
alias foo=echo; foo bar
or
{
alias foo=echo
foo bar
}
will try to run foo
as the alias is not defined at parse time yet. Also, some shells parse the whole input of an eval
or .
(source) before executing any of it.
So the only portable and reliable way to use aliases in scripts is to define them and then eval
or .
the code that uses them.