Using case Statements
An if and elif chain is the right tool when each branch depends on a different condition. When one value must be compared against many possible answers, the chain becomes long and repetitive. The case statement was designed for exactly that job. It takes a single value, compares it with a list of patterns, and runs the commands attached to the first pattern that matches. It is the usual way to write menus, to handle commands such as start and stop, and to sort file names by extension.
Understanding the Concept
A case statement asks one question, "what is this value?", and offers several labeled answers. Compare the two styles for a script that reacts to the word in $1:
if [ "$1" = "start" ]; then
echo "Starting service"
elif [ "$1" = "stop" ]; then
echo "Stopping service"
elif [ "$1" = "restart" ]; then
echo "Restarting service"
else
echo "unknown command"
fi
The same logic as a case statement needs the subject only once:
case "$1" in
start) echo "Starting service" ;;
stop) echo "Stopping service" ;;
restart) echo "Restarting service" ;;
*) echo "unknown command" ;;
esac
The second form is shorter and easier to scan, and adding a new command means adding one line. A case statement also supports wildcard patterns and several alternatives per branch, which a chain of = comparisons cannot express without extra work.
Syntax
case WORD in
PATTERN1)
commands
;;
PATTERN2 | PATTERN3)
commands
;;
*)
commands
;;
esac
The parts are:
casestarts the statement andesac(which iscasespelled backwards) ends it.WORDis the value being tested. It is expanded first, so it can be a variable, a command substitution, or plain text.inseparates the word from the list of branches.- Each branch begins with one or more patterns, separated by
|, and a closing parenthesis). - The commands of a branch follow the parenthesis and may span many lines.
- Two semicolons,
;;, end the branch. - The pattern
*matches anything, which makes it the natural default branch. It belongs last, because the first matching pattern wins.
Short branches can sit on one line, with the ;; at the end. Longer branches are usually written with the commands on their own lines, indented one level deeper than the pattern.
Basic Example
fruit="apple"
case "$fruit" in
apple) echo "red or green" ;;
banana) echo "yellow" ;;
*) echo "unknown fruit" ;;
esac
Output:
red or green
Running the same statement for several values shows the other branches:
for fruit in apple banana kiwi; do
case "$fruit" in
apple) echo "$fruit: red or green" ;;
banana) echo "$fruit: yellow" ;;
*) echo "$fruit: unknown fruit" ;;
esac
done
Output:
apple: red or green
banana: yellow
kiwi: unknown fruit
Understanding the Example
When Bash reaches case "$fruit" in, it first expands the word. With fruit=apple, the word becomes apple. It then reads the patterns from top to bottom and compares the word with each. The pattern apple matches, so Bash runs echo "red or green" and, at the ;;, leaves the statement. It does not look at the remaining patterns. For kiwi, neither apple nor banana matches, but * matches everything, so the default branch runs.
The for loop in the second part (covered in lesson 78) repeats the statement for three values. Each pass runs exactly one branch.
How Matching Works
The patterns in a case statement are shell patterns, the same wildcard patterns used for file names (lesson 52). They are not regular expressions. The most useful pieces are:
| Pattern | Matches |
|---|---|
abc | exactly the text abc |
* | any text, including an empty string |
? | exactly one character |
[abc] | one character from the set |
[a-z] | one character from the range |
[[:digit:]] | one character from a named class such as digits |
a|b | either a or b (alternatives, written with a plain | between patterns) |
The whole word must match the whole pattern. The pattern app does not match apple, but app* does. Lesson 76 covers pattern matching in depth, including extended patterns.
Alternatives with |
One branch can answer to several spellings:
for ans in y Y yes YES n No maybe; do
case "$ans" in
y|Y|yes|YES) echo "$ans -> yes" ;;
n|N|no|NO) echo "$ans -> no" ;;
*) echo "$ans -> unrecognized" ;;
esac
done
Output:
y -> yes
Y -> yes
yes -> yes
YES -> yes
n -> no
No -> unrecognized
maybe -> unrecognized
The pipe character here is not a pipeline. Inside the pattern list, it separates alternative patterns. Note that No is not accepted, since the list contains no and NO but not No. Patterns are case-sensitive, which is why the listing must name every spelling or use one of the techniques shown in the section on case-insensitive matching.
Wildcards and Character Sets
A single statement can classify file names, with each branch using a different kind of pattern:
for f in report.txt photo.png data.csv README archive.tar.gz .hidden ""; do
case "$f" in
*.txt) t="text" ;;
*.png|*.jpg) t="image" ;;
*.tar.gz|*.tgz) t="archive" ;;
.*) t="hidden" ;;
[A-Z]*) t="starts with capital" ;;
"") t="empty" ;;
*) t="other" ;;
esac
echo "[$f] -> $t"
done
Output:
[report.txt] -> text
[photo.png] -> image
[data.csv] -> other
[README] -> starts with capital
[archive.tar.gz] -> archive
[.hidden] -> hidden
[] -> empty
Every name ends up in exactly one branch. data.csv matches nothing before *, so it lands in the default. README has no extension but begins with a capital letter, so [A-Z]* catches it. The empty string matches only the pattern "", which is a pair of quotes with nothing between them. The pattern * would also match an empty string, but because "" comes first, it is chosen instead.
The question-mark and bracket patterns work the same way:
for c in a ab abc; do
case "$c" in
?) echo "$c: one char" ;;
??) echo "$c: two chars" ;;
*) echo "$c: longer" ;;
esac
done
for c in 7 x Q; do
case "$c" in
[0-9]) echo "$c: digit" ;;
[a-z]) echo "$c: lowercase" ;;
[[:upper:]]) echo "$c: uppercase" ;;
esac
done
Output:
a: one char
ab: two chars
abc: longer
7: digit
x: lowercase
Q: uppercase
The First Match Wins
Patterns are checked in order, and the search stops at the first match. When two patterns could both match, the order decides:
v=abc
case "$v" in
a*) echo "first: a*" ;;
abc) echo "second: abc" ;;
*) echo "default" ;;
esac
Output:
first: a*
The value abc matches both a* and abc, but the broader pattern comes first, so the more specific one is never reached. Place specific patterns before general ones, and keep * at the very end.
Quoting Inside case
Quoting changes whether a character is a wildcard, just as it does in filenames. A quoted asterisk is an ordinary character:
case 'a*' in "a*") echo "quoted star is literal and matches a*" ;; esac
case "abc" in "a*") echo "wrong" ;; *) echo "quoted star does not match abc" ;; esac
Output:
quoted star is literal and matches a*
quoted star does not match abc
The same rule applies to a pattern stored in a variable. Unquoted, the variable's value is used as a pattern. Quoted, it is compared as plain text:
pat='a*'
case "abc" in "$pat") echo "matches" ;; *) echo "quoted variable: literal text, no match" ;; esac
case "abc" in $pat) echo "unquoted variable: pattern, matches abc" ;; *) echo "no" ;; esac
Output:
quoted variable: literal text, no match
unquoted variable: pattern, matches abc
This matches what [[ ]] does with the right side of == (lesson 69). Quote the pattern part to force an exact comparison, and leave it unquoted when you want wildcards.
The word after case, unlike a command argument, does not undergo word splitting or filename expansion. A value with spaces stays together even without quotes, and an unset variable becomes an empty string:
s="hello world"
case $s in "hello world") echo "matched with spaces" ;; esac
unset u
case $u in "") echo "unquoted unset variable works too" ;; esac
Output:
matched with spaces
unquoted unset variable works too
Even so, quoting the word, as in case "$s" in, is a good habit because it works the same way in every context and reads consistently.
Exit Status of a case Statement
A case statement returns the status of the last command it ran. If no pattern matched and there was no default, it returns 0:
case "zzz" in
a) echo "a" ;;
b) echo "b" ;;
esac
echo "status with no match: $?"
case x in x) false ;; esac; echo "status after false: $?"
case x in x) true ;; esac; echo "status after true: $?"
case x in x) ;; esac; echo "status of an empty branch: $?"
Output:
status with no match: 0
status after false: 1
status after true: 0
status of an empty branch: 0
Because a missing match is not an error, a script that must react to unexpected values needs an explicit default branch with *). Without it, a typo in an argument passes silently.
Terminators: ;;, ;& and ;;&
The usual terminator ;; ends the statement as soon as a branch has run. Bash has two more terminators, which change what happens next:
| Terminator | Effect after the branch runs |
|---|---|
;; | stop; leave the case statement |
;& | continue into the next branch's commands without testing its pattern |
;;& | continue testing the remaining patterns; run any that also match |
n=1
case $n in
1) echo "one" ;&
2) echo "two (fall through)" ;;
3) echo "three" ;;
esac
Output:
one
two (fall through)
The ;& after the first branch makes Bash run the commands of the next branch even though n is not 2. The second branch ends with ;;, so three never runs.
case "ab" in
a*) echo "matches a*" ;;&
*b) echo "matches *b" ;;&
*) echo "matches *" ;;
esac
Output:
matches a*
matches *b
matches *
Here ;;& tells Bash to keep checking. The word ab matches all three patterns, so all three branches run. These two terminators exist only in Bash, so scripts that must run under sh should avoid them.
Missing the terminator on the last branch is allowed, because the esac ends the statement anyway:
case y in
y) echo "no terminator on last branch"
esac
Output:
no terminator on last branch
Adding ;; on every branch, including the last, keeps the code uniform and makes it safe to add new branches later.
Syntax Errors to Recognize
Forgetting a closing parenthesis or ;; produces errors that look unrelated to the real cause:
case x in x) echo hi esac
Output:
bash: -c: line 2: syntax error: unexpected end of file
Here esac was read as an argument to echo, because the branch has no ;; or newline before it, so the statement never ends. The -c in the message appears because this command was given to bash -c; in a script file, the script name and line number appear in its place.
case x in x echo hi;; esac
Output:
bash: -c: line 1: syntax error near unexpected token `echo'
The pattern x has no closing parenthesis, so Bash sees echo where it expected ).
Case-Insensitive Matching
Because patterns are case-sensitive, there are three common ways to accept yes, Yes and YES. The first is to name each letter's two forms in a bracket expression:
case "YES" in [yY][eE][sS]) echo "bracket form matched" ;; esac
Output:
bracket form matched
The second is to lowercase the value first with the ${var,,} expansion (lesson 70):
answer="YeS"
case "${answer,,}" in yes) echo "lowercased matched" ;; esac
Output:
lowercased matched
The third is the nocasematch shell option, which makes both case and [[ ]] ignore case until it is turned off again:
shopt -s nocasematch
case "YES" in yes) echo "nocasematch: matched" ;; esac
shopt -u nocasematch
case "YES" in yes) echo "bad" ;; *) echo "case-sensitive again: no match" ;; esac
Output:
nocasematch: matched
case-sensitive again: no match
Remember to switch the option off afterwards, so that later case statements in the script behave normally. The shopt command is covered in lesson 149.
Numbers Are Matched as Text
A case statement compares text only. It has no concept of numeric value, so 07 and 7 are different:
case 07 in
7) echo "07 matches 7" ;;
07) echo "07 matches 07 as text" ;;
esac
Output:
07 matches 07 as text
For comparisons such as "greater than ten", use the integer operators from lesson 73. A case statement is best for exact values, lists of values and shapes of text.
Portability
The core syntax, case, in, patterns, |, ), ;; and esac, is part of the POSIX standard and works in every shell. Run through Dash, the examples with alternatives, wildcards and bracket expressions all produced the expected output:
dash alt ok
dash glob ok
dash bracket ok
The ;& and ;;& terminators are not portable. Dash rejects ;&:
sh: 1: Syntax error: "&" unexpected
This is another reason case is often preferred over [[ ]] for scripts that must run under sh. It gives pattern matching without needing [[.
Practical Applications
A service-style script that acts on its first argument and rejects anything else with a usage message:
#!/usr/bin/env bash
case "$1" in
start) echo "Starting service" ;;
stop) echo "Stopping service" ;;
restart) echo "Restarting service" ;;
status) echo "Service is running" ;;
"") echo "usage: $0 {start|stop|restart|status}" >&2; exit 2 ;;
*) echo "unknown command: $1" >&2; exit 2 ;;
esac
Saved as cmd.sh, the script prints Starting service for bash cmd.sh start and exits with status 0. With no argument, it prints usage: cmd.sh {start|stop|restart|status} to standard error and exits with status 2. With bogus, it prints unknown command: bogus and also exits with status 2. Handling the empty string separately gives a more helpful message than the generic default. Lesson 127 builds on this pattern when parsing script arguments, and lesson 130 introduces getopts for options.
A script that reports what kind of file each argument is, based on its extension:
for f in "$@"; do
case "$f" in
*.jpg|*.jpeg|*.png|*.gif) echo "$f: image" ;;
*.mp3|*.wav) echo "$f: audio" ;;
*.sh) echo "$f: shell script" ;;
*.tar.gz|*.zip) echo "$f: archive" ;;
*) echo "$f: unknown type" ;;
esac
done
Run with cat.jpg song.mp3 run.sh backup.tar.gz notes.txt "my photo.png", it printed:
cat.jpg: image
song.mp3: audio
run.sh: shell script
backup.tar.gz: archive
notes.txt: unknown type
my photo.png: image
The quoted "$f" keeps the name with a space in it as one value. The extension .tar.gz is listed as one pattern, which works because * matches any text before it.
A script that adapts to the operating system by testing the output of a command. The $(...) substitution comes from lesson 48:
case "$(uname -s)" in
Linux) echo "running on Linux" ;;
Darwin) echo "running on macOS" ;;
*) echo "other OS" ;;
esac
On the test machine the output was running on Linux. On macOS, uname -s prints Darwin, which is why that word appears in the second branch.
A case statement inside a loop, using continue to skip some values. Loop control is covered in lesson 84:
for n in 1 2 3 4 5; do
case $n in
2|4) continue ;;
esac
echo "n=$n"
done
Output:
n=1
n=3
n=5
The values 2 and 4 match the first branch, and continue jumps back to the top of the loop before the echo runs. For values with no matching branch, the statement does nothing, so the echo executes. The same pattern is the basis of menus built with read (lesson 31) and select (lesson 86).