Case Statements for Pattern Matching
Uses case statements with glob patterns, fall-through behavior, and default cases for implementing command dispatch and input classification logic.
Code
#!/usr/bin/env bash
set -euo pipefail
classify_file() {
local file=$1
case "$file" in
*.jpg|*.jpeg|*.png|*.gif|*.webp)
echo "Image file: $file" ;;
*.mp3|*.wav|*.flac|*.ogg)
echo "Audio file: $file" ;;
*.mp4|*.avi|*.mkv|*.webm)
echo "Video file: $file" ;;
*.txt|*.md|*.rst)
echo "Text file: $file" ;;
*.sh|*.bash)
echo "Shell script: $file" ;;
*.tar|*.gz|*.zip|*.bz2)
echo "Archive: $file" ;;
*)
echo "Unknown type: $file" ;;
esac
}
dispatch() {
local command=$1
shift
case "$command" in
start|up)
echo "Starting service: $*"
;;
stop|down)
echo "Stopping service: $*"
;;
restart|reload)
echo "Restarting service: $*"
;;
status)
echo "Checking status: $*"
;;
-h|--help|help)
echo "Usage: $0 {start|stop|restart|status}"
;;
*)
echo "Unknown command: $command" >&2
echo "Use --help for usage" >&2
return 1
;;
esac
}
parse_input() {
local input=$1
case "$input" in
[0-9]*)
echo "Starts with number" ;;
[a-z]*)
echo "Starts with lowercase" ;;
[A-Z]*)
echo "Starts with uppercase" ;;
-*)
echo "Starts with dash (option)" ;;
*)
echo "Other: $input" ;;
esac
}
classify_file "photo.jpg"
classify_file "script.sh"
classify_file "unknown.xyz"
dispatch start "my-service"
dispatch status "my-service"
parse_input "123abc"
parse_input "hello"
parse_input "--flag"case statements match values against glob patterns with | for alternatives. Patterns support * (any), ? (single char), [...] (character sets). The ) terminates patterns, ;; terminates cases. * as the last pattern catches all unmatched values. Case statements are faster and more readable than if-elif chains for multiple comparisons.
Interactive Tools for This Topic
Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
Report a problem with this exampleOpens a pre-filled issue on GitHub.