Creating alias commands in Bash to make life easier
In Category Bash
If you have longer command or a set of commands that needs to be run repeatedly and you are tired of typing full command or using history to run them, then alias commands are designed for you. Using history to run set of commands is not so comfortable.
You can define your own command using aliases based on existing commands. For example, you want to mimic Microsoft Windows command line in UNIX or Linux, you define an alias for windows command with the equivalent command in UNIX or Linux. Look at the following example in which a “dir” command is defined using alias.
[mark@techpulp ~]# alias dir='ls -l' [mark@techpulp ~]# dir drwxr-xr-x 2 mark mark 4096 2009-01-21 06:14 Desktop drwxr-xr-x 2 mark mark 4096 2009-02-28 19:32 Documents -rw-rw-r-- 1 mark mark 29509 2009-02-09 15:46 Dog_Olive.jpg drwxr-xr-x 6 mark mark 4096 2009-02-22 23:04 Download [mark@techpulp ~]#
Similarly “md” command used in Microsoft Windows to create a directory while “mkdir” is used in UNIX or Linux. The following examples create alias commands “md” and “rd”.
[mark@techpulp ~]# alias md='mkdir' [mark@techpulp ~]# alias rd='rmdir' [mark@techpulp ~]# alias deltree='rm -rf'
You can group set of commands using semicolon to run them at once. This combined command can be assigned to an alias command to make it easy to type. For example the following alias determines the differences between two directories and find the count of modified files.
[mark@techpulp ~]# alias mcount='diff -r dir1 dir2 | grep ^diff | wc -l'
The following alias deletes CVS directories recursively.
[mark@techpulp ~]# alias rmcvs='find . -iname CVS -type d | xargs rm -rf'
The following alias makes it easy for you to move to a specific directory.
[mark@techpulp ~]# alias cddoc='cd ~/Documents/Office/General/' [mark@techpulp ~]# cddoc [mark@techpulp General]#
Creating an alias is same as creating a new command so you can refer one alias command in another or you can club multiple alias commands in to one and so on. You can place these commands in ~/.bashrc so that they will be available for you by default.
But alias commands may not be suitable if you you have complex logic. In such case it is better to write a script and place it in any directory that is covered by $PATH.
You can view list of all alias command as shown below:
[mark@techpulp ~]# alias alias l.='ls -d .* --color=auto' alias ll='ls -l --color=auto' alias ls='ls --color=auto' alias vi='vim' alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde' [mark@techpulp ~]#
You can remove aliases using “unalias” command as shown below:
[mark@techpulp ~]# unalias deltree
Very useful commands. Thanks!