As scripts grow, long if and elif blocks get harder to read. case gives you a cleaner structure for command routing and pattern matching.
Table of Contents
This post shows practical case patterns you can drop into daily scripts.
Case Syntax Fundamentals
Pattern Matching Options
Applying case to CLI Scripts
Series Navigation
Case syntax fundamentals
Basic shape of case in esac
case tests one value against several patterns and runs the first matching branch.
case "$target" in
start)
echo "starting service"
;;
stop)
echo "stopping service"
;;
esacEach branch ends with ;; to prevent fall-through behavior.
Default branch with star pattern
Use * as a fallback when no explicit pattern matches.
case "$target" in
start)
echo "starting"
;;
stop)
echo "stopping"
;;
*)
echo "unknown command: $target"
exit 1
;;
esacPattern matching options
Match multiple choices in one branch
Use | to match several accepted values.
case "$env_name" in
prod|production)
echo "production mode"
;;
stage|staging)
echo "staging mode"
;;
*)
echo "default mode"
;;
esacUse glob style patterns
Patterns can match prefixes and suffixes directly.
case "$filename" in
*.log)
echo "log file"
;;
backup-*)
echo "backup file"
;;
*)
echo "other file type"
;;
esacApplying case to CLI scripts
Map subcommands to functions
This pattern scales well when one script offers multiple actions.
#!/usr/bin/env bash
build() {
echo "running build"
}
deploy() {
echo "running deploy"
}
status() {
echo "showing status"
}
command_name="${1:-}"
case "$command_name" in
build)
build
;;
deploy)
deploy
;;
status)
status
;;
*)
echo "usage: $0 {build|deploy|status}"
exit 1
;;
esacReplace complex if chains
If you are doing repeated [[ "$x" == "value" ]] checks on one variable, case is usually easier to maintain.
This keeps routing logic compact and makes unknown input handling explicit.
Next in this series
Next, we will cover loops with for, while, and until so your scripts can process repeated work safely and predictably.