Unix How To: Aliases and Functions

With the right set of functions and aliases, Unix users can save themselves time and trouble and make their Unix accounts a lot nicer to use. In today's "how to", we're going to look at a simple function for setting up aliases and another that makes an alias-like change to a system command.

As most readers are probably aware, aliases provide a way for Unix users to give shorter or more familiar names to commands they use routinely. Some people use them to force the use of certain command options -- for example, adding -i to the rm(remove) command so that the system always confirms a deletion with the user before removing a file. Others use aliases to assign shorter names to commands they use all the time. The string "ltr", for example might be made to represent the "ls -ltr" (long listing in reverse time order) command. Still others might like to type "dir" instead of "ls" or "move" instead of "mv" (don't ask me why!).

For aliases to become a permanent part of a user's environment, s/he can add the alias commands, such as those shown below, to one of the "dot files" that are read whenever s/he logs in.

$ tail -5 .bashrc
# aliases
alias rm="rm -i"
alias ltr="ls -ltr"
alias dir="ls"
alias move="mv"

Easy enough, but let's make it even easier. The function below, which you could place in the user's .bashrc file, would allow him to create and capture aliases without even having to remember which file s/he should be storing them in. All s/he has to do is type "mkalias" followed by the name and the definition of the alias s/he is creating.

function mkalias ()
    if [[ $1 && $2 ]]
        echo "alias $1=\"$2\"" >> ~/.bashrc
        alias $1="$2"

This mkalias function expects two arguments (ignoring anything else typed on the line) and adds the alias definition to the bottom of the user's .bashrc file.

For example, your user might type this on the command line:

mkalias rm "rm -i"

The "if [[ $1 && $2 ]]" test ensures that two arguments have been provided with the mkalias call. The combination of double quotes (") and escaped double quotes (\") ensures that we capture the values the user types and put quotes around the definition of the alias. When the user types:

$ mkalias cl clear
$ mkalias ltr "ls -ltr"

we capture:

alias cl="clear"
alias ltr="ls -ltr"

Of course, you need to be sure that the user's .bashrc file is sourced on login. This is usually done via the .bash_profile. This form of the alias command works on bash and related shells. The syntax for aliases and start up files will be different for shells like csh.

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.

Copyright © 2010 IDG Communications, Inc.

IT Salary Survey: The results are in