Control Flow and LogicLesson 2.3
Bash case statement for multi-branch logic
case syntax, pattern matching, wildcard patterns, | alternation in case, ;; vs ;& vs ;;& terminators, case vs if-elif chain, argument parsing with case
case: Cleaner Multi-Branch Logic
Use case instead of long if-elif chains when matching a variable against known values. It supports glob patterns, not just exact strings.
#!/usr/bin/env bash
env="$1"
case "$env" in
production | prod)
echo "Deploying to PRODUCTION"
;;
staging | stage)
echo "Deploying to STAGING"
;;
dev | development)
echo "Deploying to DEV"
;;
*)
echo "Unknown environment: $env" >&2
exit 1
;;
esacPattern Matching in case
filename="report.csv"
case "$filename" in
*.csv)
echo "Parsing CSV"
;;
*.json | *.jsonl)
echo "Parsing JSON"
;;
*.log)
echo "Reading log"
;;
*)
echo "Unsupported format" >&2
exit 1
;;
esacParsing CLI Arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--output|-o)
output_dir="$2"
shift 2
;;
--verbose|-v)
verbose=true
shift
;;
*)
echo "Unknown flag: $1" >&2
exit 1
;;
esac
doneThe *) catch-all at the end of a case block is your safety net โ always include it to handle unexpected inputs explicitly.
