Red Hat Linux 7 Unleashed

Red Hat Linux 7 Unleashed

By William Ball

Functions

As with other programming languages, shell programs also support functions. A function is a piece of a shell program that performs a particular process that can be used more than once in the shell program. Writing a function helps you write shell programs without duplication of code.

The following is the format of a function in pdksh and bash for function definition:

func(){
   Statements
}

You can call a function as follows:

func param1 param2 param3

The parameters param1 , param2 , and so on are optional. You can also pass the parameters as a single string--for example, $@. A function can parse the parameters as if they were positional parameters passed to a shell program.

The following example is a function that displays the name of the month or an error message if you pass a month number. Here is the example, in pdksh and bash:

#!/bin/sh
Displaymonth() {
   case $1 in
      01 | 1) echo "Month is January";;
      02 | 2) echo "Month is February";;
      03 | 3) echo "Month is March";;
      04 | 4) echo "Month is April";;
      05 | 5) echo "Month is May";;
      06 | 6) echo "Month is June";;
      07 | 7) echo "Month is July";;
      08 | 8) echo "Month is August";;
      09 | 9) echo "Month is September";;
      10) echo "Month is October";;
      11) echo "Month is November";;
      12) echo "Month is December";;
      *) echo "Invalid parameter";;
   esac
}

Displaymonth 8

The preceding program displays the following:

Month is August

Share ThisShare This

Informit Network