Sooner or later, you will discover that you run certain commands with a particular set of options or perform a task involving two or three commands over and over. While the history mechanism is useful for this if you have performed these actions recently, bash offers another mechanism for defining and recalling a specified set of commands and options.
The alias mechanism allows you to define a simple command line sequence and recall it with a single keyword or alias. Defining an alias follows a syntax similar to assigning a variable.
The syntax for creating an alias is :
alias alias_name='command_sequence'
Example :
alias lls="ls -l | less"
To define an alias, invoke the command alias, give the alias name immediately followed by an = and the alias definition or command sequence. If the command sequence contains spaces, redirection, variable references, or multiple commands and delimiters, it must be quoted. So you must quote it pretty much every time.
To invoke the alias, simply its name at the prompt :
lls
To list the definition of a particular alias, use alias and the alias name :
alias lls
To remove an alias definition, use unalias and the alias name :
unalias lls
If you redefine an alias, the old definition is overwritten.
Other things to know about aliases. An alias :
In bash, an alias cannot call itself. Try the following :
alias recall="echo 'in recall'; recall"
recall
You should see the first message and then an error indicating it does not recognize "recall"
When a command line is processed by the command interpreter and it finds a defined alias name, it substitutes the name with its definition. It does this before the command or commands in the command line are run. Because of this, it is possible to fudge on the alias' inability to take command line arguments.
Experiment : #(Make sure you are in your home directory and ls is not an alias.)
cd $HOME unalias ls #(Define the alias lls as follows and run it :)
alias lls="ls -l" lls #(Now try :) lls /etc #(Redefine the alias lls as follows :)
alias lls="ls -l|less" lls #(Now try :) lls /etc/passwd |
For the second try, look closely at the output and you should see that it is a listing of your home directory. The alias gets expanded to "ls -l|less /etc". Because the pipe is the command delimiter for the ls -l and input to less is already piped from the ls -l, the "/etc" argument is not needed by less and ignored.
Arguments (and options) specified after an alias name will be appended to the end of alias expansion and only if the make sense at that position, will they be used.