Case statements

Beginner · 16 min

Match one value against several glob patterns with case, handle several spellings with |, set a default with *), and know which terminators need Bash 4.

Before thisGlobbing and wildcardsConditionals with if, test and double bracketsLoops - for, while and until

Learn Linux TV · 16 min

Case statements

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Learn Linux TVReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `case value in pattern) commands ;; esac` runs the commands of the first pattern that matches the value.
  • Patterns are globs, not regular expressions. `|` separates alternatives and `*)` as the last branch is the default.
  • Each branch ends with `;;`. Bash 4 adds `;&` to fall through into the next branch and `;;&` to keep testing later patterns.
  • The value needs no quotes, but a variable used as a pattern is a glob unless you quote it.
  • `case` is a better fit than a chain of `if`/`elif` whenever one value is compared against many fixed shapes.

When an if ladder gets long

Suppose you want to sort HTTP status codes into classes: 2xx, 3xx, 4xx, 5xx. With if, that is four elif branches, each repeating a test against the same variable. The shape is always the same: one value, compared against several patterns, with a different action for each. For that shape, Bash has a dedicated construct.

case $value in
  pattern1) commands ;;
  pattern2) commands ;;
  *)        default ;;
esac

Read it from the top. Bash checks value against each pattern in order and runs the commands of the first one that matches, then stops. (The name esac is case backwards, which is the same joke as fi for if.)

logsum v4: counting by class

Here is the log tool, now classifying every request. The patterns are globs where ? matches one character:

#!/usr/bin/env bash
# logsum v4: count requests by status class
ok=0 redirect=0 client=0 server=0 other=0
while read -r status; do
  case $status in
    2??) ok=$((ok + 1)) ;;
    3??) redirect=$((redirect + 1)) ;;
    4??) client=$((client + 1)) ;;
    5??) server=$((server + 1)) ;;
    *)   other=$((other + 1)) ;;
  esac
done < <(awk '{ print $8 }' "${1:-logs/access.log}")
echo "2xx=$ok 3xx=$redirect 4xx=$client 5xx=$server other=$other"
$ ./logsum
2xx=104 3xx=40 4xx=32 5xx=24 other=0

The totals add up to 200, and the 5xx=24 agrees with the awk count from earlier lessons. ShellCheck reported nothing. The loop is fed with < <(...) so the counters live in the main shell, as the loops lesson explained.

Patterns, not regular expressions

case patterns are the same globs you use on file names: *, ?, and [...]. Anything about regular expressions you learned from grep or sed doesn’t apply here. A | separates alternatives, so one branch can cover several spellings, and *) at the end is the default:

case $reply in
  y|Y|yes|YES) echo "confirmed" ;;
  n|N|no|NO)   echo "cancelled" ;;
  "")          echo "nothing given" ;;
  *)           echo "unrecognised: $reply" ;;
esac
$ for a in y YES n maybe ""; do ./answer.sh "$a"; done
confirmed
confirmed
cancelled
unrecognised: maybe
nothing given

Without the *) branch, an unmatched value does nothing, and the script carries on, so a typo goes unnoticed. For that reason, I’d always write the default branch, even if it only prints an error.

Patterns can match file names by shape, too. This version took five names and sorted them:

$ ./ext.sh src.tar.gz main.c .env notes.txt x.tgz
src.tar.gz: tarball
main.c: C source
.env: hidden
notes.txt: unknown
x.tgz: tarball

The branches were *.tar.gz|*.tgz, *.[ch], .* and *. Order matters, since the first match wins, so put specific patterns before general ones.

Quoting rules inside case

The value after case doesn’t need quotes, because no splitting happens there, which is why case $status in is safe. The patterns are different. A variable used as a pattern is treated as a glob unless you quote it:

$ v='*'; case abc in $v) echo "unquoted var is a pattern";; esac; case abc in "$v") echo no;; *) echo "quoted var is literal";; esac
unquoted var is a pattern
quoted var is literal

If you want a literal comparison against user input, quote it. And for case-insensitive matching, shopt -s nocasematch made case YES in yes) match in my test, saving you from listing every spelling.

Fall-through, and the Bash 4 line

A branch normally ends with ;;, which stops the case. Bash 4 added two other terminators: ;& carries on into the next branch’s commands without testing it, and ;;& carries on testing the remaining patterns.

$ ./fall.sh a; ./fall.sh c
a
b (reached from a or b)
c
c* also runs

Argument a printed its own line and then ran branch b, while c used ;;& to test the later c* pattern too. These forms matter in Bash 5.3 but not on stock macOS. I ran /bin/bash -n on that script and Bash 3.2 reported “syntax error near unexpected token &'", so a script using them fails to parse on a Mac's default shell, before any line runs. Plain ;;` works everywhere.

About the video

Learn Linux TV’s “How To Write Bash Scripts In Linux - Complete Guide (Part 13 - Case Statements)” is 15 minutes 50 seconds and was uploaded in November 2022. I couldn’t read a transcript. The description says it covers using case to simplify conditional logic and match specific patterns. It is in English, and it is from the same series as the first-script and functions lessons. A shorter You Suck at Programming video on matching and falling through is linked as a second view.

Where this fits

case is the natural tool for dispatching on a command-line argument. Before that, you need a way to package code with a name: functions, arguments and scope.

Check yourself

  1. 01Why does `case $status in 2??) ...` match 200 and 204 but not 20?

    Each `?` matches exactly one character, so `2??` is a three-character pattern starting with 2. Patterns are globs, not regular expressions.

  2. 02How do you make one branch accept `y`, `Y` and `yes`?

    Separate the alternatives with a pipe: `y|Y|yes) ...`. Any of them selects the branch.

  3. 03What does the final `*)` branch do, and what happens without one?

    It matches anything that earlier patterns didn't, so it acts as the default. Without it, an unmatched value runs nothing and the `case` quietly returns.

  4. 04Your script uses `;&` and fails on a stock Mac with a syntax error. Why?

    The fall-through terminators arrived in Bash 4. macOS's `/bin/bash` is 3.2 and rejects `;&` at parse time. Use `;;` or run the script with a newer Bash.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark