Sams Teach Yourself Shell Programming in 24 Hours
(Publisher: Macmillan Computer Publishing)
Author(s): Sriranga Veeraraghavan
ISBN: 0672314819
Publication Date: 01/01/99

Previous Table of Contents Next


Hour 14
Functions

Shell functions provide a way of mapping a name to a list of commands. Shell functions are similar to subroutines, procedures, and functions in other programming languages.

Think of them as miniature shell scripts that enable a name to be associated with a set of commands. The main difference is that a new instance of the shell begins in order to run a shell script, whereas functions run in the current shell.

Creating and Using Functions

The formal definition of a shell function is as follows:

name () { list ; }

A function binds a name to the list of commands that composes the body of the function. The ( and ) characters are required at the function definition.

The following examples illustrate valid and invalid function definitions:

lsl() { ls –l ; }    # valid
lsl { ls -l ; }         # invalid

In this example, the first definition is valid but the second one is not because it omits the parentheses after the string lsl.

This example also demonstrates a common use of functions. Because the original shell, sh, did not have the alias keyword common to more recent shells, all aliases were defined in terms of shell functions. A frequently encountered example of this is the source command. The sh equivalent is the . command. Many converts from csh use the following function to simulate the source command:

source() { . "$@" ; }

As this example shows, shell functions have a separate set of arguments than the shell script to which they belong. You explore this feature later in the chapter.


Tip:  
An important feature of shell functions is that you can use them to replace binaries or shell built-ins of the same name.

An example of this is

cd () { chdir ${1:-$HOME} ; PS1="'pwd'$ " ; export PS1 ; }

This function replaces the cd command with a function which changes directories but also sets the primary shell prompt, $PS1, to include the current directory.


Invoking a Function

To invoke a function, only its name is required, thus typing

$ lsl

on the command line executes the lsl() function, but typing

$ lsl()

does not work because sh interprets this as a redefinition of the function by the name lsl. In most versions of the shell, typing lsl() results in a prompt similar to the following:

>

This is a prompt produced by the shell when it expects you to provide more input. Here the input it expects is the body of the function lsl.

Function Examples

In this section you will look at two examples of how functions are used to gain a better understanding of their role in shell scripting.

Listing Your Path

A simple task that is well-suited to a function is listing the current value of your PATH, with each directory listed on a single line. The basic shell code is

OLDIFS="$IFS"
IFS=:
for DIR in $PATH ; do echo $DIR ; done
IFS="$OLDIFS"

Here you save the value of IFS in the variable OLDIFS and then set IFS to :. Because IFS is the Internal Field Separator for the shell, you can use the for loop to cycle through the individual entries in PATH. When you are finished, restore the value of IFS.


Note:  
The shell uses the value of the variable IFS to split up a string into separate words. Normally it is set to the space and tab character, enabling the shell to figure out that the following string
this is a string

contains four words. The shell uses the value of IFS to determine how many options are supplied to a command, script, or shell function and how many items are specified to a for loop.

In the previous example, you set the value of IFS to be the colon character. This means that the shell sees four words in the following string:

this:is:a:string

To wrap this up in a function, insert the function name and the brackets as follows:

lspath() {
    OLDIFS="$IFS"
    IFS=:
    for DIR in $PATH ; do echo $DIR ; done
    IFS="$OLDIFS"
}

Now you can run the function as follows:

$ lspath

On my system the output is

/sbin
/bin
/usr/bin
/usr/sbin
/opt/bin
/usr/ucb
/usr/ccs/bin
/usr/openwin/bin

One of the main uses of this function is to check whether a particular directory is in your PATH. For example, to check whether /usr/dt/bin is in my path, I can do the following:

$ lspath | grep "/usr/dt/bin"


Previous Table of Contents Next