Alias Substitution

The shell supports a feature called aliases, which are basically command shortcuts or abbreviations. During input processing, and before any other command processing such as expansion, the shell examines the command name of each simple command to determine if it is an unquoted alias name. If the command name is an alias, it is replaced with that alias value.

If the alias substitution results in a new command name that is an alias that has not already been substituted (to prevent infinite recursion), this process is repeated, recursively, until no additional substitution can be made.

Additionally, whenever an alias is substituted that ends in a <blank> character, the shell also performs alias substitution on the next word in the command.

The alias and unalias utilities are used to manage and inspect alias definitions.

Example

$ alias x='echo hello!'
$ x
hello!
$ x x
hello! x
$ alias x='echo hello! '
$ x x
hello! echo hello!
$ alias y='x'
$ y
hello!
$ y y
hello! echo hello!
$ alias y='x x'
$ y
hello! echo hello!

Aliasing Reserved Words

There is a special exception for reserved words; in a context where a reserved word would be recognized, it cannot be a candidate for alias substitution:

$ alias !='echo "<!>"'
$ ! true
$ echo $?
1

However, in contexts where a word wouldn’t be recognized as a reserved word, it can be subsituted:

$ VAR='' ! true
<!> true
$ alias x='echo '
$ x !
<!>

Alias Best Practices

Aliases are typically used in interactive sessions to define short names for longer commands, or to automatically pass default arguments to a command. Aliases can be very confusing, as demonstrated above, and they can override any command, even special built-ins. The only way to reliably circumvent aliases is to quote command names.

Additionally, different shells interpret ambiguities in the POSIX alias specification differently; for example, bash ignores aliases ending with a <blank> after the first level of recursion, but another POSIX shell, yash does not. There are also ambiguities about how aliases should work with, for example, eval. This means that aliases are generally not portable, and their use should be avoided as much as possible.

As an alternative, modern style guides typically recommend the use of shell functions wherever one might be tempted to use an alias. For example, instead of the common alias la='ls -la', a function of the same name could be defined to serve the same purpose,

la() {
   ls -la "$@"
}