tags:

views:

40

answers:

4
+1  Q: 

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.

A: 

Check out this post, it has your answer: Alias inside script

cschar
+2  A: 

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
GreenMatt
interesting, the man page even implies the need for shopt, but for bash 3.2.39 it's turned on by default.
mvds
+1  A: 

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.

mvds
A: 

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.

jilles