case Statement
In this page:
Basic case Syntax
case compares a single value against a list of patterns in order and runs the commands under the first pattern that matches, ending each branch with ;;. The whole statement is closed with esac.
Example: Basic case Syntax
#!/bin/bash
fruit="banana"
case $fruit in
apple)
echo "It's an apple"
;;
banana)
echo "It's a banana"
;;
*)
echo "Unknown fruit"
;;
esac
Login to try C/C++/Java/PHP code in the editor
Matching Multiple Patterns with |
A single branch can match several alternative patterns by separating them with | (pipe), which acts as an or between patterns. This avoids duplicating the same commands under multiple separate branches.
Example: Matching Multiple Patterns with |
#!/bin/bash
answer="y"
case $answer in
y|Y|yes|YES)
echo "Confirmed"
;;
n|N|no|NO)
echo "Declined"
;;
*)
echo "Unrecognized response"
;;
esac
Login to try C/C++/Java/PHP code in the editor
Glob Patterns in case
case patterns use the same glob wildcards as filename matching: * matches any string, ? matches a single character, and [abc] matches any one of the listed characters. This makes case convenient for classifying things like file extensions.
Example: Glob Patterns in case
#!/bin/bash
filename="archive.tar.gz"
case $filename in
*.txt)
echo "Text file"
;;
*.tar.gz|*.tgz)
echo "Compressed tarball"
;;
*)
echo "Unknown type"
;;
esac
Login to try C/C++/Java/PHP code in the editor
Fallthrough with ;;&
Normally case stops after running the first matching branch, but the Bash-specific ;;& terminator lets execution keep testing later patterns even after a match, rather than exiting the statement. This is useful when more than one branch might legitimately apply to the same value.
Example: Fallthrough with ;;&
#!/bin/bash
value="15"
case $value in
[0-9]*)
echo "Starts with a digit"
;;&
1*)
echo "Starts with a 1"
;;
esac
Login to try C/C++/Java/PHP code in the editor
- Forgetting the double semicolon
;;at the end of each pattern's commands; without it Bash keeps looking for the next;;and merges branches together unexpectedly. - Thinking
casepatterns are regular expressions; they are actually glob-style wildcard patterns (*,?,[...]), not full regex syntax. - Forgetting the closing
esac(case spelled backwards) to end the statement.
- Syntax:
case value in pattern1) commands ;; pattern2) commands ;; esac. - Patterns support glob wildcards (
*,?,[abc]) and can be combined with|to match multiple alternatives in one branch, e.g.y|Y). *)as the final pattern acts as a catch-all default branch, matching anything not caught earlier.;;&(Bash extension) lets execution continue testing subsequent patterns even after a match, instead of stopping at the first match.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: