A case statement is another form of branching. It is a great alternative to if..elif when you have many conditions, such as if you want to specify sub-commands. You specify an expression (typically a variable) to match on, then one or more patterns. The statements for a pattern is executed if it matches the expression. A pattern and associated statements is called a clause and must be terminated with ;;.

case EXPRESSION in

  PATTERN_1)
    STATEMENTS
    ;;
  PATTERN_2)
    STATEMENTS
    ;;
  *)
    STATEMENTS
    ;;
esac

Here is an example of how it could be used in a script:

#!/bin/bash
subcommand=$1
case $subcommand in
  start)
    echo "Starting service"
    ;;
  stop | kill)
    echo "Stopping service"
    ;;
  status)
    echo "Service is running"
    ;;
  *)
  echo "Unknow sub-command $1"
  ;;
esac

This case statement in bash is similar to the switch statement in many programming language, except it automatically breaks on a matching statement.

If we have multiple patterns for which we want to execute the same set of commands, then we can use | to specify multiple patterns for the same clause.

The * pattern matches everything. Therefore, it is often used to specify a default clause for when none of the other patterns match the expression.

There are other special characters that can be used. You can read about it here.

Challenge

Write a Fizz Buzz script using case.

Hint.