Chapter 13: Case Statement
—
Case statement is generally used to simplify complex conditionals when you have multiple different choices, and is preferred over nested if-else statements.
Syntax
—
1 case EXPRESSION in
2
3 PATTERN_1)
4 # code block
5 ;;
6 PATTERN_2)
7 # code block
8 ;;
9
10 PATTERN_N)
11 # code block
12 ;;
13 *)
14 # code block
15 ;;
16 esac
- The
)operator terminates a pattern list. - Each clause must be terminated with
;; - It is a common practice to use the wildcard (*) as a final pattern to define the default case. This pattern will always match.
- If no pattern is matched, the return status is zero. Otherwise, the return status is the exit status of the executed commands.
Example
—
1 while true; do
2 clear
3 echo "Chose 1, 2 or 3"
4 echo "1: See logged in users"
5 echo "2: Date in 90 days"
6 echo "3: Quit"
7 read -sn1
8 case "$REPLY" in
9 1) who;;
10 2) date --date="90 days";;
11 3) exit 0;;
12 *) echo "Incorrect option selected. Please select again"
13 esac
14 read -n1 -p "Enter any key to continue"
15 done