Linux: alias Command


Most of us use the same commands over and over again. The alias command can help simplify your life when it comes to typing out the same long drown out commands. Think of it as a shortcut command.

Lets say that you always type hostname;uptime;date. You can create an alias where it will run the same commands when you type the single letter h.

First of all, lets view all the current alias commands on your computer.

$ alias

Example:

$ alias
alias d='date'
alias u='uptime'

As you can see, I’ve already created two alias. If nothing shows up on your prompt, then you do not have any alias’ created yet.

How do you add an alias temporarily?

$ alias =''

Example:

$ alias h='hostname;uptime;date'

Lets check our alias commands.

$ alias

Example:

$ alias
alias d='date'
alias h='hostname;uptime;date'
alias u='uptime'
$ h
Server.local
23:44  up 42 days, 36 mins, 3 users, load averages: 0.11 0.07 0.07
Thu Feb 17 23:44:29 PST 2011

The alias h has been added to our alias list.

How do you remove it?

$ unalias 

Example:

$ unalias h
$ alias
alias d='date'
alias u='uptime'
$ h
-bash: h: command not found

It’s that simple.

How do you add an alias permanently?

All you need to do is add the alias to your bash file.


Remembering bash files:

When Bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile (global) and then /etc/bashrc (global), if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login,  ~/.profile and ~/.bashrc (in that order) within your personal account, and reads and executes commands from the first one that exists and is readable.

Global settings:
/etc/profile
/etc/bashrc

Personal settings:
~/.bash_profile
~/.bash_login
~/.profile
~/.bashrc


I personally use .bash_profile. I would just need to vi .bash_profile and add alias h=’hostname;uptime;date’.

$ vi .bash_profile
alias h='hostname;uptime;date'

To apply the new setting, all I would have to do is source .bash_profile or log out and log back in.

$ source .bash_profile

There you have it. The basics of how to use the alias command.

, ,