Visiting aliases
An alias is a shortcut to replace typing a long-command sequence. In this recipe, we will see how to create aliases using the alias command.
How to do it...
These are the operations you can perform on aliases:
- Create an alias:
$ alias new_command='command sequence'This example creates a shortcut for the apt-get install command:
$ alias install='sudo apt-get install'Once the alias is defined, we can type install instead of sudo apt-get install.
- The
aliascommand is temporary: aliases exist until we close the current terminal. To make an alias available to all shells, add this statement to the~/.bashrcfile. Commands in~/.bashrcare always executed when a new interactive shell process is spawned:
$ echo 'alias cmd="command seq"' >> ~/.bashrc- To remove an alias, remove its entry from
~/.bashrc(if any) or use theunaliascommand. Alternatively,alias example=should unset the alias namedexample. - This example creates an alias for
rmthat will delete the original and keep a copy in a backup directory:
alias rm='cp $@ ~/backup && rm $@'Note
When you create an alias, if the item being aliased already exists, it will be replaced by this newly aliased command for that user.
There's more...
When running as a privileged user, aliases can be a security breach. To avoid compromising your system, you should escape commands.
Escaping aliases
Given how easy it is to create an alias to masquerade as a native command, you should not run aliased commands as a privileged user. We can ignore any aliases currently defined, by escaping the command we want to run. Consider this example:
$ \commandThe \ character escapes the command, running it without any aliased changes. When running privileged commands on an untrusted environment, it is always a good security practice to ignore aliases by prefixing the command with \. The attacker might have aliased the privileged command with his/her own custom command, to steal critical information that is provided by the user to the command.
Listing aliases
The alias command lists the currently defined aliases:
$ aliasalias lc='ls -color=auto' alias ll='ls -l' alias vi='vim'