Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

case: Matching Patterns

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

The shortcut

Order patterns from most specific to most general, then read the block like a sieve: drop the value in at the top and stop at the first hole it fits.

The answer "Yes" falls through the sieveStep 1 of 4
  1. First pattern: [yY]

    Matches exactly one character. Yes has three, so it does not fit.

Drills

Answer fast — trust the rule.

quick drill

Which pattern matches Yes, yes and y, but not no?

quick drill

What ends one branch of a case statement?

quick drill

A case block lists *) first, then daily). What happens when the value is daily?

quick drill

Are case patterns regular expressions?

Remember

  • case tries patterns top to bottom; the first match runs, and ;; ends it.
  • Most specific first, catch-all *) last.
  • Patterns are wildcards, not regular expressions; close the block with esac.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainAccept any kind of yes

backup.sh asks Continue? [y/n] with read. Write a case statement that continues on y, Y, yes or Yes, stops with status 0 on n or no, and stops with status 2 on anything else. Explain how case chooses a branch and why the order of the patterns matters.