A shell alias is a shortcut to reference a command. It can be used to avoid typing long commands or as a means to correct incorrect input. For common patterns it can reduce keystrokes and improve efficiency. A simple example is setting default options on commands to avoid having to type them each time a command is run.
For the following example suppose that a user prefers to confirm deleting a file before using the
rm command. The rm command supports this with the
rm -i file.txt remove file.txt? y
To avoid forgetting to use the
-i option each time an alias can be created so that each time
rm is run it will use the
-i option and prompt the user to confirm.
Building on the previous example an alias can be directly set in the shell as follows.
alias rm='rm -i'
Now when the
rm command is run it will use the alias and the
rm file.txt remove file.txt?
Note that setting an alias in this way only works for the life of a shell session. When the shell is closed the alias will be lost. To make an alias persist across shell sessions and reboots a configuration file for the shell should be used. For
bash this is the
.bashrc file. If you are using
zsh it is the
.bashrc file can be used to set configuration for a shell. In this example a local user’s
.bashrc file will be used. If you are running the
zsh shell use a file called
~/.bashrc file in your preferred text editor. If it does not exist create it.
.bashrc files aliases can now be added. The format is simple. First declare the command you wish to alias, then specify the command to run instead.
alias rm='rm -i'
For this example we replace
rm -i so that the user is prompted before deleting the file.
.bashrc file is saved the shell needs to be reloaded for the alias to take effect.
The alias should now be available and typing
rm will be interpreted as
The following are some practical examples of using aliases.
# ensure git commits are signed alias git commit='git commit -S' # shorthand for vim alias v="vim" # setting preferred options on ls alias ls='ls -lhF' # prompt user if overwriting during copy alias cp='cp -i' # prompt user when deleting a file alias rm='rm -i' # always print in human readable form alias df="df -h"
Have an update or suggestion for this article? You can edit it here and send me a pull request.