Bash: Case Statements
A case statement compares a value with several patterns and runs the commands for the first matching pattern.
Basic Case Statement
Choosing a command
case "$1" in
start)
echo "Starting the service"
;;
stop)
echo "Stopping the service"
;;
*)
echo "Usage: $0 {start|stop}"
;;
esac
Each pattern is followed by ). End a branch with ;;, and close the statement with esac. The * branch is a fallback for values that do not match another pattern.
Matching Several Values
Combining patterns
case "$1" in
yes|y|Y)
echo "Continuing"
;;
no|n|N)
echo "Stopping"
;;
*)
echo "Please answer yes or no"
;;
esac
Separate alternative patterns with | when they should run the same block of commands.
Wildcard Patterns
Matching file names
case "$1" in
*.sh)
echo "Bash script"
;;
*.txt|*.md)
echo "Text document"
;;
*)
echo "Unknown file type"
;;
esac
Case patterns use shell wildcards: * matches any number of characters, ? matches one character, and bracket expressions such as [[:digit:]] match a character class.
Case Patterns for Validation
Checking a positive integer
case "$1" in
''|*[!0-9]*)
echo "Enter a positive integer"
;;
*)
echo "Valid integer: $1"
;;
esac
The first pattern matches an empty value or any value containing a non-digit. The second pattern is reached only when every character is a digit.
Regular Expressions
Use =~ for regex matching
if [[ "$1" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
echo "Date format is valid"
else
echo "Use YYYY-MM-DD"
fi
Bash case patterns use shell wildcard syntax, not regular expressions. For a true regular-expression check, use [[ string =~ regex ]]. Keep the regex unquoted so Bash can interpret it as a pattern.
Reading Input in a Loop
Simple menu
while true; do
read -r -p "Choose start, status, or quit: " command
case "$command" in
start)
echo "Starting"
;;
status)
echo "Running"
;;
quit|exit)
break
;;
*)
echo "Unknown command"
;;
esac
done
A case statement is useful for command-line menus because each supported command gets a readable branch and the fallback handles unexpected input.