Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
Home Bash Guide for Beginners Conditional statements Using case statements | |||
See also: Simple applications of if | |||
Search the VIAS Library | Index | |||
Using case statementsSimplified conditionsNested 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. Initscript exampleInitscripts 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.
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.
|
|||
Home Bash Guide for Beginners Conditional statements Using case statements |