Site Feed

Wednesday, December 2, 2009

Bash Alias

An alias is a built-in way of modifying the way a command works, or it is used as a shortcut for another command. For example, you may find that you often type "ls -l", or "ls -ltr", and think it would be nice if you could type less characters. You can create an alias, so that all you would have to type is "ll", instead of "ls -l."

To add an alias to your .bashrc file:

$ vi ~/.bashrc

Insert these lines:

alias ls='ls --color=tty'

alias ll='ls -l'

In order for the new alias to take effect, you can open a new console, login again, or simply source your .bashrc file. You also have the option of running bash again to open a new shell, or just running the alias command. What do I mean by source the file? You can either run a script, or have the shell read the variables in a script without actually running it. This is called sourcing a file, and is accomplished by typing either "source", or "." followed by the file to source, e.g.

$ source ~/.bashrc

or

$ . ~/.bashrc

Sometimes the word source is easier to read than a dot, but either method will work fine.

Note that you don't need to be root to access your home directory. "~/" is a shortcut for wherever your home directory happens to be (e.g. /mountpoint/home/me, or /home/users/someone). Also, the dot "." is used for hidden files, so if you do

$ ls ~/

it won't show up, but if you do

$ ls -a ~/

it will.

There are some common aliases you may have by default. To view your current aliases, type alias by itself, or "alias -p":

$ alias -p
alias cp='cp -i'
alias l.='ls -d .* --color=tty'
alias ll='ls -l --color=tty'
alias ls='ls --color=tty'
alias mv='mv -i'
alias rm='rm -i'
alias vi='vim'

Other Uses

"What else can this be used for?", you ask. Anything you use often enough -- usually something smaller than a script, but too long to type frequently. How about changing to a common directory? Of course, to go home, type:

$ cd

To go to the previous directory, type:

$ cd -

Maybe you would like something like "sales" to take you to /home/dept/sales.

alias sales='cd /home/dept/sales'


Unalias


What happens if you make a mistake, or you use your account on a host that has a shell that does not support your alias? For example, you log into a sun box, and the ls alias is not valid. The quick fix is to simply run "unalias ls."

So, go have some fun with aliases. Here are a few ideas to try:

alias h='hostname'
alias myprogram='/usr/local/bin/myprogram'
alias taillog='tail -f /var/log/messages'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

No comments: