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

The case Statement

The case Statement

The case statement is used to execute statements depending on a discrete value or a range of values matching the specified variable. In most cases, you can use a case statement instead of an if statement if you have a large number of conditions.

The format of a case statement for bash is as follows:

case str in
 str1 | str2)
  Statements;;
 str3|str4)
  Statements;;
 *)
  Statements;;
esac

You can specify a number of discrete values — such as str1, str2, and so on — for each condition, or you can specify a value with a wildcard. The last condition should be * (asterisk) and is executed if none of the other conditions is met. For each of the specified conditions, all the associated statements until the double semicolon (;;) are executed.

You can write a script that echoes the name of the month if you provide the month number as a parameter. If you provide a number that isn't between 1 and 12, you get an error message. The script is as follows:

#!/bin/sh
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

You need to end the statements under each condition with a double semicolon (;;). If you do not, the statements under the next condition will also be executed.

The last condition should be default and is executed if none of the other conditions is met. For each of the specified conditions, all the associated statements until breaksw are executed.

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


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