Книга: Fedora™ Unleashed, 2008 edition

Using Functions in Shell Scripts

Using Functions in Shell Scripts

As with other programming languages, shell programs also support functions. A function is a piece of a shell program that performs a particular process; you can reuse the same function multiple times within the shell program. Functions help eliminate the need for duplicating code as you write shell programs.

The following is the format of a function in bash:

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 from the command line as command-line arguments, but instead use values passed inside the script. For example, the following script uses a function named Displaymonth() that displays the name of the month or an error message if you pass a month number out of the range 1 to 12. This example works with 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 output:

Month is August

Оглавление книги


Генерация: 1.087. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз