Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Shell Aliases

An alias is a short form of a command. The built-in alias command creates simple abbreviations for the current Bash session.

To create an alias, use the alias command to assign a command and its switches a name.

$ alias lf='ls -qFl'
$ lf
-rw-r-----  1 kburtch  devgroup   10809 Apr 6 11:00 assets.txt
-rw-r-----  1 kburtch  devgroup   4713 Mar 9 2000 mailing_list.txt

Typing the alias command by itself, or with the -p switch, lists the current aliases.

$ alias
alias lf='ls -qFl'

Bash interprets an alias only once, allowing the aliasing of a command with its own name.

$ alias ls='ls -qF' # Bash isn't confused

Normally, only the first word of a command is checked for an alias. As a special exception, if the last character in the alias string is a blank, Bash checks the next word in the command to see whether it is also an alias.

There is no method for giving arguments to an alias. If arguments are needed, define a more powerful shell function instead.

The built-in unalias command removes an alias. Use the -a switch to remove them all.

Most Linux distributions have aliases defined for common commands. dir, for example, is often an alias for ls. Some distributions define an alias for commands such as rm -i to force user prompting, which is not required by default. This can be a problem for some users such as experienced Unix programmers who are used to working with these features disabled. Use unalias to remove any aliases that you don't want to use.

Aliases mixed with shell functions can be confusing because aliases are expanded only when a line from a script is read. If aliases are used in a shell function, they are expanded when the shell function is defined, not when it is executed. For this reason, it is safer to avoid aliases altogether in shell scripts. However, they can be turned on in scripts using the shopt –s expand_aliases command.

  • + Share This
  • 🔖 Save To Your Account