Thursday, January 28, 2016

Function and Alias in Bash

People are lazy in general. Sometimes, it is simply annoying to type long commands in bash with lots of options. Let us see how we can use bash functions and alias to relieve stress of typing too much.

alias helps us to shorten a long command. On Linux, I use $ ls --color=auto -CF commands quite a lot. However, it becomes annoying typing the command repeatedly. What one can do is create an alias to shorten this as
$ alias ls='ls --color=auto -CF'

Now, when you type the command $ ls, it will essentially execute $ ls --color=auto -CF command. In many cases, you may want to write the alias command in ~/.bashrc for Linux and ~/.bash_profile for Mac OS X to be executed every time you open up the terminal. In fact, on my system (Ubuntu 14.04 LTS), the default ~./bashrc file already contains some alias commands as below:
alias ls='ls --color=auto'
...
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'


Hence, the command $ l will actually execute $ ls -CF, which in turn will execute $ ls --color=auto -CF, i.e., $ l is a nested alias for $ ls --color=auto -CF.

By the way, the utility ls is a bit different on a Mac OS X system, since it is a BSD version of ls whereas on Linux it is GNU version of ls. The two are very similar but some of the options are different. In any case, the use of alias is identical, so I will not go into the difference of BSD ls and GNU ls here.

Next up is bash function. Although alias can shorten the commands quite significantly, it does not support arguments. That is when the bash function comes very handy. Consider the example below.

 To search for files and directories, I often use the command $ find / -name name_to_search 2> /dev/null. Again, typing this command repeatedly makes my fingers very tired. I'd like to create an alias for this, but I can't because I need to supply the argument name_to_search and alias does not support it. So, I will need to make a function here.
$ f() { find / -name $1 2> /dev/null; }

Now if I run $ f bash, it will execute the command $ find / -name bash 2> /dev/null. Note that $1 is the first argument, $2 is the second argument, and so forth. For example, the function below will take two arguments.
$ ff() { find / -name $1 -type $2 2> /dev/null; }

Now, if I execute $ ff bash f, this will execute $ find / -name bash -type f 2> /dev/null. Again, you can save these functions in the ~/.bashrc for Linux for ~/.bash_profile for Mac OS X to load the function automatically at the startup of the terminal.

No comments:

Post a Comment