14.5.8 The case Command
The case command is a multiway branching command used as an alternative to if/elif commands. The value of the case variable is matched against value1, value2, and so forth, until a match is found. When a value matches the case variable, the commands following the value are executed until the double semicolons are reached. Then execution starts after the word esac (case spelled backward).
If the case variable is not matched, the program executes the commands after the *), the default value, until ;; or esac is reached. The *) value functions the same as the else statement in if/else conditionals. The case values allow the use of shell wildcards and the vertical bar (pipe symbol) for ORing two values.
FORMAT
case variable in value1) command(s) ;; value2) command(s) ;; *) command(s) ;; esac
Example 14.30.
(The Script) #!/bin/bash # Scriptname: xcolors 1 echo -n "Choose a foreground color for your xterm window: " read color 2 case "$color" in 3 [Bb]l??) 4 xterm -fg blue -fn terminal & 5 ;; 6 [Gg]ree*) xterm -fg darkgreen -fn terminal & ;; 7 red | orange) # The vertical bar means "or" xterm -fg "$color" -fn terminal & ;; 8 *) xterm -fn terminal ;; 9 esac 10 echo "Out of case command"
Creating Menus with the here document and case Command
The here document and case command are often used together. The here document is used to create a menu of choices that will be displayed to the screen. The user will be asked to select one of the menu items, and the case command will test against the set of choices to execute the appropriate command.
Example 14.31.
(From the .bash_profile File) echo "Select a terminal type: " 1 cat <<- ENDIT 1) unix 2) xterm 3) sun 2 ENDIT 3 read choice 4 case "$choice" in 5 1) TERM=unix export TERM ;; 2) TERM=xterm export TERM ;; 6 3) TERM=sun export TERM ;; 7 esac 8 echo "TERM is $TERM."