Bash Script – Why Can’t I Use Alias in Script Even If Defined Above?

aliasbashshell-script

I have a very wierd case… If I run a script with /bin/bash, it can't recognize aliases that I set even inside the script. And the most strange thing is

$ cat -n test.sh
    1 #!/bin/bash
    2 alias somecommand='ls -alF'
    3 alias
    4 somecommand
$ ./test.sh
alias somecommand='ls -alF'
./test.sh: line 4: somecommand: command not found

… as shown above, if I run the command "alias" in the script it turns out that bash has taken somecommand into the aliases, but if I run the somecommand itself it will still not be recognized!

Everything is right if I use the command "sh" to run the script.. so is it a bug of bash? Or is there something I'm missing?

Any help is appreciated!

Best Answer

Simply don't use aliases in scripts. It makes little sense to use a feature designed for interactive use in scripts. Instead, use functions:

somecommand () {
    ls -alF
}

Functions are much more flexible than aliases. The following would overload the usual ls with a version that always does ls -F (arguments are passed in $@, including any flags that you use), pretty much as the alias alias ls="ls -F" would do:

ls () {
    command ls -F "$@"
}

The command here prevents the shell from going into an infinite recursion, which it would otherwise do since the function is also called ls.

An alias would never be able to do something like this:

select_edit () (
    dir=${1:-.}
    if [ ! -d "$dir" ]; then
        echo 'Not a directory' >&2
        return 1
    fi
    shopt -s dotglob nullglob
    set --
    for name in "$dir"/*; do
        [ -f "$name" ] && set -- "$@" "$name"
    done
    select file in "$@"; do
        "${EDITOR:-vi}" "$file"
        break
    done
)

This creates the function select_edit which takes directory as an argument and asks the user to pick a file in that directory. The picked file will be opened in an editor for editing.

The bash manual contains the statement

For almost every purpose, aliases are superseded by shell functions.

Related Question