Библиотека сайта rus-linux.net
7.3. Using case statements
7.3.1. Simplified conditions
Nested if statements might be nice, but as soon as you are confronted with a couple of different possible actions to take, they tend to confuse. For the more complex conditionals, use the case syntax:
case EXPRESSION
in CASE1
) COMMAND-LIST;; CASE2
) COMMAND-LIST;; ... CASEN
) COMMAND-LIST;; esac
Each case is an expression matching a pattern. The commands in the COMMAND-LIST for the first match are executed. The "|" symbol is used for separating multiple patterns, and the ")" operator terminates a pattern list. Each case plus its according commands are called a clause. Each clause must be terminated with ";;". Each case statement is ended with the esac statement.
In the example, we demonstrate use of cases for sending a more selective warning message with the disktest.sh
script:
|
Of course you could have opened your mail program to check the results; this is just to demonstrate that the script sends a decent mail with "To:", "Subject:" and "From:" header lines.
Many more examples using case statements can be found in your system's init script directory. The startup scripts use start and stop cases to run or stop system processes. A theoretical example can be found in the next section.
7.3.2. Initscript example
Initscripts often make use of case statements for starting, stopping and querying system services. This is an excerpt of the script that starts Anacron, a daemon that runs commands periodically with a frequency specified in days.
case "$1" in start) start ;; stop) stop ;; status) status anacron ;; restart) stop start ;; condrestart) if test "x`pidof anacron`" != x; then stop start fi ;; *) echo $"Usage: $0 {start|stop|restart|condrestart|status}" exit 1 esac |
The tasks to execute in each case, such as stopping and starting the daemon, are defined in functions, which are partially sourced from the /etc/rc.d/init.d/functions
file. See Chapter 11 for more explanation.