Next: The test command
Up: Looping and Making Choices
Previous: The ifthenelse Structure
General form:
case value in
choice1) commands ;;
choice2) commands ;;
esac
- The case statement lets a shell script choose from a list of
alternatives.
- The value portion can come from shell variables, shell-script
arguments or command outputs.
- choice1 and choice2 are labels that identify potential
choices of action. The shell's pattern matching abilities can be used in the
choice labels.
- The ) is used to identify labels, the double semicolon serves to
separate one choice from the next and the esac marks the end of the
case statement. The double semicolon, however, is not mandatory after
the final choice.
- Several commands can be executed for a given choice by separating them
with command separators (newline or semicolon).
- The words case and esac MUST come after a command
separator. (Say, did you know that already?)
- A choice labeled *) matches any value, so it is often used as the
last choice to act as a catchall. (Making it the first choice would cause the
first choice to match any value, and all the other choices would never be
reached.)
- If no choices match and if there is no catchall choice, then nothing is
done.
- The bar symbol | serves as an or operator with which more than
one label may be attached to the same response.
case $animal in
cat | dog ) echo "$animal is a pet" ;;
crocodile | snake) echo "$animal is no pet" ;;
esac
Roger Hampel
Mon Feb 2 09:39:25 MET 1998