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.


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:


sum() {
if [ -z "$2" ]; then
echo $1
b=`sum $@`
echo `expr $a + $b`

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.

6 Responses to “Bourne/Bash Shell Script Functions”

  1. November 21, 2008 at 5:57 am, kishroe said:

    simple to understand and very good for bushing up the unix


  2. December 01, 2008 at 7:06 am, Khushbu said:

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


  3. July 30, 2009 at 9:52 am, vaiju said:

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


  4. September 23, 2009 at 5:46 am, Anonymous said:

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

    if [ -z "$2" ]
    echo “sum: $1″
    local a=`expr $1 + $2`
    shift 2
    sum $a $@
    sum 3 5 34


  5. September 30, 2009 at 9:21 am, Penton said:

    You can use return to return the result generated within a function. Please read more about this within the following URL:
    (Example 23-3. Maximum of two numbers)


  6. December 03, 2009 at 5:17 am, guille said:

    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!


Leave a Reply