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"Report a problem with this exampleOpens a pre-filled issue on GitHub.