How to Use Bash Case Statement

Users can add as many elif clauses as they want into an if/then/elif/then/else statement to test as many conditions as they need. However, as more are added, the statement and its logic becomes increasingly harder to read and comprehend. For these more complex situations, Bash offers another conditional structure known as case statements. The case statement utilizes the following syntax:

case [VALUE] in
   [PATTERN1])
      [STATEMENT]
      ...
      [STATEMENT]
      ;;
   [PATTERN2])
      [STATEMENT]
      ...
      [STATEMENT]
      ;;
esac

The case statement attempts to match [VALUE] to each [PATTERN] in order, one by one. When a pattern matches, the code segment associated with that pattern is executed, with the ;; syntax indicating the end of the block. All other patterns remaining in the case statement are then skipped and the case statement is exited. As many pattern/statement blocks as needed can be added.

To mimic the behavior of an else clause in an if/then/elif/then/else construct, simply use * as the final pattern in the case statement. Since this expression matches anything, it has the effect of executing a set of commands if none of the other patterns are matched.

The case statements are widely used in init scripts. The following code section is an example of how they are commonly used to take different actions, depending on the argument passed to the script.

case "$1" in
   start)
      start
      ;;
   stop)
      rm -f $lockfile stop
      ;;
   restart)
      restart
      ;;
   reload)
      reload
      ;;
   status)
      status
      ;;
   *)
      echo "Usage: $0 (start|stop|restart|reload|status)"
      ;;
esac

If the actions to be taken are the same for more than one pattern in a case statement, the patterns can be combined to share the same action block, as demonstrated in the following example. The pipe character, |, is used to separate the multiple patterns.

case "$1" in
   ...
   reload|restart)
       restart
       ;;
   ...
esac