Professional Documents
Culture Documents
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:
anny ~/testdir> cat disktest.sh
#!/bin/bash
# This script does a very simple test for checking disk space.
space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f
case $space in
[1-6]*)
Message="All is quiet."
;;
[7-8]*)
Message="Start thinking about cleaning out some stuff. There's a partition that is $spa
;;
9[1-8])
Message="Better hurry with that new disk... One partition is $space % full."
;;
99)
Message="I'm drowning here! There's a partition at $space %!"
;;
*)
Message="I seem to be running with an nonexistent amount of disk space..."
;;
esac
anny ~/testdir>
You have new mail.
Start thinking about cleaning out some stuff. There's a partition that is 87 % full.
anny ~/testdir>
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.