Alias

From LQWiki
Jump to navigation Jump to search

An alias is simply that - another name with which to refer to a command. Aliases allow you to create shorter or more familiar names for commonly used commands. Another benefit lies in being able to not only alias the command, but the first few arguments, as well. Aliases were introduced by csh and later incorporated in bash and others.

The exact syntax used to set an alias depends on your shell. For Bourne-type shells (ksh, bash, etc., though not sh), the syntax is:

$ alias name=command

If the command has arguments, then quotes (single or double) must be used:

$ alias name="command argument ..."

For csh-type shells (csh, tcsh, etc.), quotes aren't needed:

$ alias name command [arguments ...]

As you can see, the main differences are the equals sign after the name of the alias and whether quotes are needed. When issued without arguments, alias prints a list of the currently defined aliases.

When issued at the command line an alias only takes effect for that shell. To make it permanant, the alias must be saved in one of the shell configuration files. For bash, they are ordinarily placed in the ~/.bashrc file for per-user configuration, or in /etc/profile for all users. For tcsh, the file ~/.tcshrc is the right place, or /etc/login for all users.

Examples

A simple alias for DOS users:

$ alias dir="ls -l"

Here is an example of a complicated alias:

$ alias topcom='sort ~/.bash_history | uniq -ci | sort -r | less'

This alias makes it is easy to look for frequently used commands that might merit being turned into yet more aliases.

Here is an another example to see mounted partitions:

$ alias mnt='mount | grep -i /dev/[h,s]d[a..g] | sort'

Shell functions can accomplish the same effect as aliases, but the latter are simpler. Unlike functions, they do not permit variable substitution.

For instance even something as simple as:

$ bak () { cp -a $1 $1.bak }

cannot be defined as an alias due to the variable "$1".

Setting an alias

To set an alias persistently for all users, all shells (ksh, bash, ...) and all type of shells (login shells and non-login shells) you need to

  • modify /etc/profile
for logIn shells
  • modify /etc/bash_bashrc
for non-login bash shells

remove an alias

Use unalias

See also