Bourne/Bash Shell Script Functions

Posted August 5, 2004 by Rex in Bourne shell scripting

Writing functions can greatly simplify a program. If a chunk of code is used multiple times in different parts of a script, the code can be enclosed within a function and run using only the function name.


The following example decribes the use of functions in a Bourne shell script.

#!/bin/sh

sum() {
x=`expr $1 + $2`
echo $x
}

sum 5 3
echo "The sum of 4 and 7 is `sum 4 7`"

When run, the script will output the value 8 (the sum of 5 and 3) followed by the text “The sum of 4 and 7 is 11” on the next line. Within the function, optional arguments passed to the function (as in the 5 3 following the function call of sum at the bottom) can be accessed like arguments to a shell script. $1 accesses the first parameter, $2 accesses the second parameter, and [email protected] accesses all parameters.

A more elaborate example will extend the sum function to add together more than two values:

#!/bin/sh

sum() {
if [ -z "$2" ]; then
echo $1
else
a=$1;
shift;
b=`sum [email protected]`
echo `expr $a + $b`
fi
}

sum 5 3 9

This script outputs the answer 17 (the sum of 5, 3, and 9). The script calls itself reciprocally to generate the sum of an arbitrary length set of numbers. The shift command is the key to this function. When shift is executed, it pops the first value off the list of parameters. The parameter list [email protected] then starts at $2 instead of $1.

The Conversation

Follow the reactions below and share your own thoughts.