Shell Case Statements
A case statement is a way to match one word against several patterns. It runs the branch whose pattern matches the word.
Match one word
The word apple matches the first branch.
fruit="apple"
case "$fruit" in
apple) echo "An apple" ;;
banana) echo "A banana" ;;
*) echo "Something else" ;;
esacCatch the rest
Mango matches no named branch, so * catches it.
fruit="mango"
case "$fruit" in
apple) echo "An apple" ;;
banana) echo "A banana" ;;
*) echo "Something else" ;;
esacMatch a choice
One branch can hold two choices with |.
day="Sat"
case "$day" in
Sat|Sun) echo "Weekend" ;;
*) echo "Weekday" ;;
esacMatch a file ending
A glob pattern matches the end of the word.
file="notes.txt"
case "$file" in
*.txt) echo "A text file" ;;
*) echo "Something else" ;;
esacExample
file="photos/beach.jpg"
case "$file" in
*.txt) echo "A text file" ;;
*.jpg) echo "A picture file" ;;
*.csv) echo "A data file" ;;
*) echo "An unknown file" ;;
esacKey points
- Case statement: case matches one word against patterns, in order.
- Pattern branch: each pattern ends with ) and its commands end with a double semicolon.
- Catch-all pattern: *) matches anything, so it catches the rest.
- Choice pattern: a|b matches a or b in one branch.
- Glob pattern: *.txt matches any word that ends in .txt.
In this example, case matches the file name against the patterns in order. *.jpg matches, so its branch prints A picture file.
Note
The first matching pattern wins, so put the catch-all last.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does *) do in a case statement?