Bash by Example: Case Statements
Handling multiple conditions cleanly with case statements as an alternative to long if-elif chains, using pattern matching with wildcards and character classes, implementing default cases with the catch-all pattern, and organizing complex conditional flows with readable case syntax.
Code
#!/bin/bash
fruit="apple"
case "$fruit" in
"apple")
echo "It's an apple."
;;
"banana" | "plantain")
echo "It's a banana or plantain."
;;
"cherry")
echo "It's a cherry."
;;
*)
echo "Unknown fruit."
;;
esacExplanation
The case statement is a powerful alternative to multiple if-elif-else blocks, especially when comparing a single variable against several possible values. It improves readability and makes the logic easier to follow. The syntax involves matching a variable against patterns, each terminated by a double semicolon ;;.
One of the key features of case is its support for pattern matching. You can use wildcards like * (matches anything) and ? (matches any single character), as well as character classes like [a-z]. You can also match multiple patterns for a single block using the pipe | symbol.
The case statement always ends with esac (case spelled backwards). It is common practice to include a "catch-all" pattern *) at the end to handle any values that didn't match previous patterns, acting like the else in an if-statement.
Code Breakdown
case "$fruit" in starts the statement. Quoting the variable is good practice to handle spaces or empty values safely."apple") is a pattern. If $fruit matches "apple", the commands following this line are executed.| allows matching multiple patterns. This block runs if the fruit is either "banana" OR "plantain".*) is the default case. It matches anything not matched by previous patterns. This is essential for error handling or default behavior.
