Using functions
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.
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.
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.