How to Use Case Statement in Bash: Syntax and Examples
In bash, use the
case statement to match a variable against multiple patterns and execute code based on the match. It starts with case VARIABLE in, followed by patterns and commands, and ends with esac. This helps simplify complex if-else chains.Syntax
The case statement checks a variable against multiple patterns. Each pattern ends with ) and is followed by commands to run if matched. Use ;; to end each pattern block. The statement ends with esac (case spelled backwards).
- case VARIABLE in: Start the case statement with the variable to test.
- pattern): Define a pattern to match the variable.
- commands: Commands to run if the pattern matches.
- ;;: Ends the commands for that pattern.
- esac: Ends the entire case statement.
bash
case VARIABLE in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default_commands
;;
esacExample
This example shows how to use a case statement to print a message based on the day of the week stored in a variable.
bash
#!/bin/bash DAY="Tuesday" case $DAY in Monday) echo "Start of the work week.";; Tuesday|Wednesday|Thursday) echo "Midweek days.";; Friday) echo "Almost weekend!";; Saturday|Sunday) echo "Weekend!";; *) echo "Not a valid day.";; esac
Output
Midweek days.
Common Pitfalls
Common mistakes when using case in bash include:
- Forgetting the
;;at the end of each pattern block causes syntax errors. - Not quoting variables can cause unexpected word splitting or globbing.
- Using incorrect pattern syntax, like missing
)after patterns. - Not including a default
*pattern to catch unmatched cases.
bash
# Wrong: Missing ;; case $var in yes) echo "Yes" # Missing ;; here no) echo "No";; esac # Right: case $var in yes) echo "Yes";; no) echo "No";; esac
Quick Reference
| Element | Description |
|---|---|
| case VARIABLE in | Start the case statement with the variable to test |
| pattern) | Pattern to match the variable |
| commands | Commands to run if pattern matches |
| ;; | Ends the commands for the current pattern |
| *) | Default pattern if no other matches |
| esac | Ends the case statement |
Key Takeaways
Use
case to simplify multiple condition checks in bash scripts.Always end each pattern block with
;; to avoid syntax errors.Include a default
* pattern to handle unexpected values.Patterns can be combined with
| to match multiple values.Quote variables when necessary to prevent word splitting or globbing.