case
The case statement matches a variable or command output against patterns and branches execution accordingly. It provides a clean way to handle multiple values, making it ideal for processing command-line arguments and building menu-driven scripts.
Syntax
case variable in
pattern1)
action1
;;
pattern2 | pattern3)
action2
;;
*)
default action
;;
esac
Pattern List
| Pattern | Description |
|---|---|
| word) | Exact match. Executes when the value equals word. |
| pat1 | pat2) | OR condition. Executes when the value matches either pattern. |
| *.txt) | Wildcard pattern. Matches any string ending in .txt. |
| [aeiou]) | Character class. Matches any one of the characters a, e, i, o, or u. |
| ?) | Matches any single character. |
| *) | Default pattern that matches everything. Place it last. |
| ;; | Terminates a pattern block (does not fall through to the next pattern). |
| ;& | Falls through and executes the next pattern block regardless (Bash 4+). |
| ;;& | Evaluates the next pattern and executes it if it matches (Bash 4+). |
Sample Code
Branches execution based on a command-line argument. Use | to combine multiple values into a single OR condition.
service.sh
#!/bin/bash
action=$1
case "$action" in
start)
echo "Starting the service"
;;
stop)
echo "Stopping the service"
;;
restart | reload)
echo "Restarting the service"
;;
status)
echo "Checking service status"
;;
*)
echo "Usage: $0 {start|stop|restart|reload|status}"
exit 1
;;
esac
bash service.sh restart
Restarting the service
Uses wildcard patterns to determine a file type by its extension.
filetype.sh
filename="report.pdf"
case "$filename" in
*.php | *.py | *.rb)
echo "Script file"
;;
*.txt | *.md | *.csv)
echo "Text file"
;;
*.jpg | *.png | *.gif)
echo "Image file"
;;
*.pdf)
echo "PDF file"
;;
*)
echo "Unknown file type"
;;
esac
bash filetype.sh
PDF file
Uses the character class [0-9] to check a numeric range.
grade_case.sh
score=85
case $score in
9[0-9] | 100)
echo "A (Excellent)"
;;
8[0-9])
echo "B (Good)"
;;
7[0-9])
echo "C (Pass)"
;;
*)
echo "D (Fail)"
;;
esac
bash grade_case.sh
B (Good)
Notes
Case patterns use shell glob patterns (wildcards), not regular expressions. If you need regex matching, use the =~ operator with if / [[ ]].
Separating patterns with | lets you group OR conditions into a single block. Compared to if-elif chains, case is more concise and easier to read.
The default pattern *) is optional, but it is recommended to always include it to handle unexpected input gracefully.
If you find any errors or copyright issues, please contact us.