Ivan
Ivan

Reputation: 1199

alias in a script

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.

Upvotes: 2

Views: 4593

Answers (3)

jilles
jilles

Reputation: 11212

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.

Upvotes: 0

mvds
mvds

Reputation: 47034

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.

Upvotes: 0

GreenMatt
GreenMatt

Reputation: 18570

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

Upvotes: 4

Related Questions