Bourne/bash shell script functions

Contributor Icon Contributed by Rex  
Tag Icon Tagged: 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 $@ 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.

 

6 Comments -


  1. kishroe said on November 21, 2008

    simple to understand and very good for bushing up the unix

  2. Khushbu said on December 1, 2008

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

  3. vaiju said on July 30, 2009

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

  4. Anonymous said on September 23, 2009

    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

  5. Penton said on September 30, 2009

    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)

  6. guille said on December 3, 2009

    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!

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -