Previous Section  < Day Day Up >  Next Section

13.6. Aliases

An alias is a bash user-defined abbreviation for a command. Aliases are useful if a command has a number of options and arguments or the syntax is difficult to remember. Aliases set at the command line are not inherited by subshells. Aliases are normally set in the .bashrc file. Because the .bashrc is executed when a new shell is started, any aliases set there will be reset for the new shell. Aliases may also be passed into shell scripts but will cause potential portability problems unless they are set directly within the script.

13.6.1 Listing Aliases

The alias built-in command lists all set aliases. The alias is printed first, followed by the real command or commands it represents.

Example 13.37.

$ alias

alias co='compress'

alias cp='cp –i'

alias mroe='more'

alias mv='mv –i'

alias ls='ls --colorztty'

alias uc='uncompress'


EXPLANATION

The alias command lists the alias (nickname) for the command and the real command the alias represents after the = sign.

13.6.2 Creating Aliases

The alias command is used to create an alias. The first argument is the name of the alias, the nickname for the command. The rest of the line consists of the command or commands that will be executed when the alias is executed. Bash aliases cannot take arguments (see "Defining Functions" on page 841). Multiple commands are separated by a semicolon, and commands containing spaces and metacharacters are surrounded by single quotes.

Example 13.38.

1   $ alias m=more

2   $ alias mroe=more

3   $ alias lF='ls -alF'

4   $ alias r='fc -s'


EXPLANATION

  1. The nickname for the more command is set to m.

  2. The alias for the more command is set to mroe. This is handy if you can't spell.

  3. The alias definition is enclosed in quotes because of the whitespace. The alias lF is a nickname for the command ls –alF.

  4. The alias r will be used instead of fc –s to recall commands from the history list by a specified pattern; for example, r vi will re-execute the last command in the history list containing the pattern vi.

13.6.3 Deleting Aliases

The unalias command is used to delete an alias. To temporarily turn off an alias, precede the alias name by a backslash.

Example 13.39.

1   $ unalias mroe

2   $ \ls


EXPLANATION

  1. The unalias command deletes the alias mroe from the list of defined aliases.

  2. The alias ls is temporarily turned off for this execution of the command only.

    Previous Section  < Day Day Up >  Next Section