A case statement compares one value against several shell patterns. It keeps command dispatch readable.

Program

Play the script to see the restart pattern choose the cycle action.

case_patterns.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

command="restart"
case "$command" in
  start) action="boot" ;;
  stop) action="halt" ;;
  restart) action="cycle" ;;
  *) action="unknown" ;;
esac
echo "$action"
  1. command ← restart

    3command="restart"4case "$command" in
    values this steprestartcommand
  2. pattern ← restart

    3command="restart"4case "$command" in5  start) action="boot" ;;
    values this steprestartpatternrestartcommand
  3. action ← cycle

    6stop) action="halt" ;;7restart) action="cycle" ;;8*) action="unknown" ;;
    values this stepcycleaction
  4. echo "$action"

    9esac10echo "$action"
    outputcycle
    values this stepcycleaction

Follow the Pattern

  1. command is set to restart.
  2. The case statement checks start, then stop, then restart, then *.
  3. restart matches the restart pattern.
  4. That branch sets action to cycle.
  5. The script prints cycle. | pattern checked | matches restart? | action | | --- | --- | --- | | start | no | - | | stop | no | - | | restart | yes | cycle | | * | not reached | - |
case `case` selects the first pattern that matches a value.
fallback pattern `*` catches values that do not match an earlier pattern.

Exercise: case_patterns.sh

Reproduce cycle, then identify the exact pattern that matches command=restart.