Bash case
case compares one value against a list of patterns and runs the block of the first one that matches. It's cleaner than a long if/elif chain when you check a single variable against many possibilities, such as menu choices, command names or file extensions.
Syntax
day="sat"
case $day in
mon|tue|wed|thu|fri)
echo "weekday"
;;
sat|sun)
echo "weekend"
;;
*)
echo "unknown day: $day"
;;
esacweekend
- Each branch is
pattern)followed by commands and ends with;;. |separates alternative patterns.*)matches anything: the default branch, by convention last.- The statement ends with
esac(casebackwards).
Patterns are globs
Patterns use the same wildcards as file names: * any text, ? one character, [...] a character set. This makes case great for classifying strings:
for file in photo.JPG notes.txt archive.tar.gz script.sh Makefile; do
case $file in
*.jpg|*.JPG|*.png) type="image" ;;
*.tar.gz|*.zip) type="archive" ;;
*.sh) type="shell script" ;;
*.*) type="other file" ;;
*) type="no extension" ;;
esac
printf '%-15s %s\n' "$file" "$type"
donephoto.JPG image
notes.txt other file
archive.tar.gz archive
script.sh shell script
Makefile no extension
The first matching branch wins, so put specific patterns before general ones: *.* would also match archive.tar.gz if it came first.
Character classes and answers
classify() {
case $1 in
[0-9]*) echo "$1: starts with a digit" ;;
[A-Z]*) echo "$1: starts with a capital" ;;
[a-z]*) echo "$1: starts with a lower-case letter" ;;
"") echo "(empty input)" ;;
*) echo "$1: starts with a symbol" ;;
esac
}
classify 42abc
classify Linux
classify bash
classify "#tag"
classify ""42abc: starts with a digit
Linux: starts with a capital
bash: starts with a lower-case letter
#tag: starts with a symbol
(empty input)
A classic use is accepting yes/no answers in any spelling:
for answer in y Yes NO maybe; do
case ${answer,,} in
y|yes) echo "$answer -> confirmed" ;;
n|no) echo "$answer -> cancelled" ;;
*) echo "$answer -> please answer yes or no" ;;
esac
doney -> confirmed
Yes -> confirmed
NO -> cancelled
maybe -> please answer yes or no
${answer,,} lower-cases the value first, so the patterns only need lower-case spellings.
Subcommands: the script dispatcher
Many tools have the form tool start, tool stop, tool status. A case on the first argument is the standard way to build that:
cat > service.sh <<'SCRIPT'
#!/usr/bin/env bash
case $1 in
start) echo "Starting app..." ;;
stop) echo "Stopping app..." ;;
restart) "$0" stop; "$0" start ;;
status) echo "app is running" ;;
*) echo "Usage: $0 {start|stop|restart|status}" >&2; exit 2 ;;
esac
SCRIPT
chmod +x service.sh
./service.sh start
./service.sh restart
./service.sh reload
echo "exit status: $?"Starting app...
Stopping app...
Starting app...
Usage: ./service.sh {start|stop|restart|status}
exit status: 2
The default branch prints a usage message to standard error (>&2) and exits with a non-zero status, which is what well-behaved command-line tools do.
Fall-through: ;& and ;;&
Bash has two less common terminators:
| Terminator | Effect |
|---|---|
;; |
Stop after this branch (normal) |
;& |
Also run the next branch's commands without testing it |
;;& |
Continue testing the remaining patterns |
level="warn"
case $level in
debug) echo "showing debug" ;&
info) echo "showing info" ;&
warn) echo "showing warnings" ;&
error) echo "showing errors" ;;
esacshowing warnings
showing errors
Starting at warn, execution falls through to error: a neat way to say "this level and everything more severe".
Test yourself
Which keyword ends a case statement?
- end
- done
- esac
- fi
What does the pattern *) do?
- Matches only
* - Matches anything: the default branch
- Matches files
- Ends the case
With case $f in *.*) ... ;; *.zip) ... ;; esac, which branch runs for a.zip?
- *.zip
- *.*
- Both
- Neither