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 can see this by typing alias with no arguments so that bash lists all the alias definitions. You would see something like this:

...
alias h='ls /home/youracct'
...

If you don’t like what your alias does and want to get rid of it, just use unalias and the name of the alias that you no longer want. For example:

unalias h

will remove the definition that we just made above. If you get really messed up, you can use unalias -a to remove all the alias definitions in your current shell session. But what if someone has created an alias for unalias? Simple, if you prefix it with a backslash, alias expansion is not performed. So use unalias-a instead.

Aliases do not allow arguments. For example, you cannot do this:

# Does NOT work, arguments NOT allowed
$ alias='mkdir $1 && cd $1'

The difference between $1 and $HOME is that $HOME is defined (one way or another) when the alias itself is defined, while you’d expect $1 to be passed in at runtime. Sorry, that doesn’t work. Use a function instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.28.108