Using shell functions is a simple way to group and store a set of commands for later execution. The general form of a shell function definition is:
name() { list; }
where name is the command name you will use to execute the function and list is a list of commands or pipelines, separated by semi-colons, which specify what task the function will perform.
For example, if you enter the following function definition:
$ ll() { ls -l; }
you will then be able to use ll as a command to perform the same task as ls -l:
$ ll drwxr-xr-x 3 PC book 1024 May 28 23:30 book
You might imagine that if you wanted to execute the command ls -al, given that the definition for ll already exists, you could achieve this with the command ll -a. Sadly, however, it isn't quite that simple. It is possible to do what we want, but in order to do it the definition for the ll function needs to be changed as follows:
$ ll() { ls -l $*; }
The addition of the $* characters means that any parameters or command line switches entered after the ll command are to be inserted into the ls -l command in place of the $* characters. Using the new definition for ll gives the expected results:
$ ll -a -rw-r--r-- 1 pc book 3392 May 29 07: 55 .bash_history -rw------- 1 pc book 25 Mar 26 1994 .profue drwxr-xr-x 3 PC book 1024 May 28 23:30 book
A more complete discussion of $* and related topics will be given in another tutorial (possibly upload tomorrow), when we look at shell programming.
The body of a shell function (between { and }) can consist of several commands or pipelines, as long as they are separated by semi-colons. Here is an example (coded in a rather inefficient way just for demonstration purposes) to display the number of files contained in a given directory. The function is called lswc as it combines the actions of these two commands:
$ lswc() { ls $* >/tmp/dir; wc -w </tmp/dir; rm /tmp/dir; }
The use of the $* characters in the definition allows lswc to take a parameter which should be the pathname of the directory upon which the command is to operate:
$ lswc /usr/bin 459