z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Using functions

z/OS UNIX System Services User's Guide
SA23-2279-00

A shell function is similar to a function in C: It is a sequence of commands that do a single job. Typically, a function is used for an operation that you tend to do frequently in a shell script. Before you can call a function in a shell script, you must define it in the script. After the function is defined, you can call it as many times as you want in the script.

As an example, consider the following piece of a shell script, showing the function definition and how the function is called in the shell script:
function td
{
    if  test -d "$1"               # test if first argument is directory
    then
        curdir=$(pwd)              # set curdir to working directory
        cd $1                      # change to specified directory
        $2                         # run specified command
        cd $curdir                 # change back to working directory
        return 0                   # return 0 if successful
    else
        echo $1 "is not a directory"
        return 1                   # return 1 if not successful
    fi
}
td /u/turbo/src.c ls               # invoking the function

The purpose of td is to go to a specified directory, run a single command, and then return to the directory from which the function was called.

To run a function, specify the function's name followed by whatever arguments it expects. To run the function td, specify the function name followed by a directory name and a command name, as shown in the last line of the foregoing example.

As you see in the td example, a function can also return a value. If the statement:
return expression
appears inside a function, the function ends and the value of expression is returned as the status, or result, of the function. In general, the returned value:
  • 0 means that the function has succeeded in its task.
  • 1 means that the function has failed.

Anytime you need to repeatedly perform the same sequence of commands in a shell script, consider defining a function to do the sequence of commands. This lets you organize a large script into smaller blocks of subroutines.

In order to make a shell function available as a shell command, the function definition must be processed by the shell that will execute the command. Typically, the user sets up a shell script (such as $HOME/.setup) that contains all of the function definitions, and sets the ENV variable to the pathname of that shell script. As the number of functions in this script grows, the time to process the function definitions causes shell initialization time to increase.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014