Skip to the workspace
Pebellslearn by building
Exit Codes and Conditionals  ›  Capstone Project

case: Matching Patterns

case 14 minA case statement compares one value against a list of wildcard patterns in order and runs the commands of the first pattern that matches.

shell bash / case: Matching Patterns

Explore each scene at your own pace.

01 · The rule

The rule

case: Matching Patterns

A case statement compares one value against a list of wildcard patterns in order and runs the commands of the first pattern that matches.

Route an input through ordered wildcard patterns and a fallback case.

backup.sh now takes a mode, daily, weekly or monthly, and asks for confirmation that people answer with y, Y, yes or Yes. A chain of elif tests for all of those would be long and repetitive. case handles "which of these shapes is this value?" in one tidy block.

The rule

case tries patterns top to bottom; the first match runs, and ;; ends it.

mode="${2:-daily}"

case "$mode" in
    daily)          keep=7 ;;
    weekly|week)    keep=4 ;;
    monthly)        keep=12 ;;
    *)              echo "Unknown mode: $mode" >&2
                    exit 2 ;;
esac

The parts:

  • case "$value" in opens the block; esac (case backwards) closes it.
  • Each branch is pattern) followed by commands and ended by ;;.
  • A vertical bar between patterns means "either of these", as in weekly|week).
  • Patterns are wildcards, not regular expressions: * anything, ? one character, [yY] one of the listed characters.
  • *) matches everything, so it is the catch-all and belongs last.

Only the first matching branch runs; the rest are skipped. That makes the order of patterns meaningful.

Here is the confirmation prompt that closes this section, combining read, case and exit codes:

read -r -p "Back up $src? [y/n] " answer
case "$answer" in
    [yY]|[yY]es) ;;                          # carry on
    [nN]|[nN]o)  echo "Cancelled"; exit 0 ;;
    *)           echo "Please answer y or n" >&2; exit 2 ;;
esac
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.