Bourne/Bash Shell Script Functions

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 $@ 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 $@`
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 $@ then starts at $2 instead of $1.

The Conversation

Follow the reactions below and share your own thoughts.

  • kishroe

    simple to understand and very good for bushing up the unix

  • Khushbu

    wat will be the output of
    [-z “$2″]; echo $;
    sh amit

  • vaiju

    The article was very useful. Thanks a ton !!!

  • Anonymous

    i found some problem with the second code
    so i modified like this :)

    #!/bin/bash
    sum()
    {
    if [ -z “$2″ ]
    then
    echo “sum: $1″
    else
    local a=`expr $1 + $2`
    shift 2
    sum $a $@
    fi
    }
    sum 3 5 34

  • Penton

    You can use return to return the result generated within a function. Please read more about this within the following URL:

    http://www.faqs.org/docs/abs/HTML/functions.html
    (Example 23-3. Maximum of two numbers)

  • http://www.juegosgratisparapc.net/ guille

    Nice tutorial, but i have a lot of problem with control structures in the { } of functions. Today i have a exam, :(
    Thks a lot! and good blog!