Monday, August 15, 2016

The Bash "Alias"

Aliases

  • Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.

    The
    first word of each simple command, if unquoted, is checked to see if it has an alias.
    If so, that word is replaced by the text of the alias.

  • The characters ‘/’, ‘$’, ‘‘’, ‘=’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name.The replacement text may contain any valid shell input, including shell metacharacters.

  • You can nest aliases.This means that if the 1st word of a simple command in a alias, then its replaced with the replacement text. However if the 1st word of the replacement text is also another alias then that is also replaced 
 
Example:
/export/home/sukul1$alias eh='echo $HOME'
/export/home/sukul1$alias ep='eh $PWD'

/export$eh
/export/home/sukul1
export$ep
/export/home/sukul1 /export

When we run ep, the 1st word (.i.e ep) is checked to see if it matches any alias, and the replacement text "eh $PWD" is used. However 1st word of replacement string is also a alias and so that is also replaced with "echo $HOME". So the command becomes "echo $HOME $PWD"


  • However very imp to note that an alias does not replace itself, which avoids the possibility of infinite recursion in handling an alias such as the following:
$ alias ls='ls -F'
This means that if the 1st word of the replacement text is same as the alias itself being replaced, then its not replaced twice.

When we run ls, its replaced with "ls -F". Here the 1st word of the replacement string is same as the alias being expanded. So its not replaced twice.

So basically 1st word of alias replacement text can be some other alias, and shell will expand that too.

  • The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text.

  • Aliases are created and listed with the alias command, and removed with the unalias command.
    There is no mechanism for using arguments in the replacement text, as in csh. If arguments are needed, a shell function should be used

  • By default the option expand_aliases is enabled for interactive shells. Check $BASHOPTS.Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.To use Aliases within scripts we need to set this shopt option.



No comments:

Post a Comment