7.3.3.1. case

The case-statement is used as follows:

case var in
  case1) commands for case1
         ...;;
  case2) commands for case2
         ...;;
  ...
esac

The variable var is checked against each case for the first pattern that matches. Then the commands for that case, terminated by ;; are executed. Wildcards can be used for the cases. Several possibilities for one case are separated by |

An example:

echo -n "Enter the name of an animal: "
read ANIMAL
echo -n "The $ANIMAL has "
case $ANIMAL in
  horse | dog | cat) echo -n "four";;
  man | kangaroo ) echo -n "two";;
  *) echo -n "an unknown number of";;
esac
echo " legs."

Note 1: the command echo -n puts the argument on the screen but without a new line.

Note 2: the read variable command reads input from screen and saves it in the variable. In this case, the text typed is saved in the variable ANIMAL. See help read for some options for this command.

The last case, with pattern *, matches everything, and will be used if none of the previous is matched.

The patterns are followed in the order given, so try to gove more specific patterns before the more general.

For clarity, especially when there are several lines in a case the ;; can also be written on a seperate line:

echo -n "Enter the name of an animal: "
read ANIMAL
echo -n "The $ANIMAL has "
case $ANIMAL in
  horse | dog | cat)
      echo -n "four"
  ;;
  man | kangaroo )
      echo -n "two"
  ;;
  *)
      echo -n "an unknown number of"
  ;;
esac
echo " legs."