The case structure is used where you want to branch to multiple program segments depending on the value of a variable. The if-else construct can be used to support multidirectional branching, but it becomes cumbersome when more than two or three branches are required. The case construct provides a convenient syntax for multi-way branching. The branch selected is based on the sequential comparison of a word and supplied patterns. These comparisons are strictly string-based. When a match is found, the corresponding list of commands will be executed. Each list of commands is terminated by a double semicolon (;;). After finishing the related list of commands, program control will continue at the esac.
case var in
pattern1)
commands
; ;
pattern2)
commands
; ;
. . .
. . .
patternn)
commands
; ;
*)
commands
; ;
esac
The value of var is checked. If this is equal to pattern1, the commands in the first block are executed. The first block ends at the ;; pattern. If the value of var matches pattern2, the commands in the second block are executed. If var matches none of the pattern values, the commands in the last block after "*)" are executed.
echo "Press w to list users"
echo "Press d to see date and time"
echo "Press p to see current directory"
echo
echo "Enter your choice: \c"
read VAR
case $VAR in
w | W ) who
; ;
d | D ) date
; ;
p | P ) pwd
; ;
* ) who echo "You have not pressed a valid key"
esac
echo "The case structure finished"