Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => Shell Script => Topic started by: Mark David on March 16, 2007, 01:19:54 PM



Title: Bourne/bash shell script functions
Post by: Mark David on March 16, 2007, 01:19:54 PM
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 describes the use of functions in a Bourne shell script.

Code:
#!/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:

Code:
#!/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.