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
casetries 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 ;;
esacThe parts:
case "$value" inopens 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 ;;
esacThe 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.
First pattern: [yY]
Matches exactly one character.
Yeshas three, so it does not fit.
Drills
Answer fast — trust the rule.
Which pattern matches Yes, yes and y, but not no?
What ends one branch of a case statement?
A case block lists *) first, then daily). What happens when the value is daily?
Are case patterns regular expressions?
Remember
casetries 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.
