Redefining Commands with alias
Problem
You’d like to slightly alter the definition of a command, perhaps so that you always use a
particular option on a command (e.g., always using -a on the ls
command or -i on the
rm command).
Solution
Use the alias feature of bash for interactive shells (only). The alias command is smart enough not to go into an endless loop when you say something like:
alias ls='ls -a'
In fact, just type alias with
no other arguments and you can see a list of aliases that are already
defined for you in your bash session. Some
installations may already have several available for you.
Discussion
The alias mechanism is a straightforward text substitution. It occurs very early in the command-line processing, so other substitutions will occur after the alias. For example, if you want to define the single letter “h” to be the command that lists your home directory, you can do it like this:
alias h='ls $HOME'
or like this:
alias h='ls ~'
The use of single quotes is significant in the first instance,
meaning that the variable $HOME will
not be evaluated when the definition of the alias is made. Only when you
run the command will the (string) substitution be made, and only then
will the $HOME variable be evaluated.
That way if you change the definition of $HOME the alias will move with it, so to
speak.
If, instead, you used double quotes, then the substitution of the
variable’s value would be made right away and the alias would be defined
with the value of $HOME substituted. You ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access