Writing case statements
Categories:
Mastering Case Statements in Bash for Conditional Logic

Explore the power and flexibility of Bash case statements for handling multiple conditional branches, offering a cleaner alternative to nested if-else structures.
In shell scripting, particularly with Bash, conditional logic is fundamental for creating dynamic and responsive scripts. While if-elif-else constructs are versatile, they can become cumbersome and difficult to read when dealing with many possible conditions. This is where the case statement shines, providing a more elegant and efficient way to handle multiple patterns or values.
Understanding the Bash case Statement
The case statement in Bash allows you to compare a single value (or variable) against several different patterns. When a match is found, the corresponding block of commands is executed. This structure is often referred to as a 'switch' statement in other programming languages. It's particularly useful for menu-driven scripts, processing command-line arguments, or handling different types of user input.
flowchart TD
A[Start]
B{Input Value}
A --> B
B -->|Pattern 1| C[Execute Commands 1]
B -->|Pattern 2| D[Execute Commands 2]
B -->|Pattern N| E[Execute Commands N]
B -->|Default (*)| F[Execute Default Commands]
C --> G[End]
D --> G
E --> G
F --> GFlowchart illustrating the decision process of a Bash case statement.
#!/bin/bash
read -p "Enter a fruit (apple, banana, cherry): " fruit
case "$fruit" in
apple)
echo "You chose a red fruit."
;;
banana)
echo "You chose a yellow fruit."
;;
cherry)
echo "You chose a small, red fruit."
;;
*)
echo "That's not one of the options."
;;
esac
echo "Script finished."
Basic example of a Bash case statement.
;; to terminate each pattern block within a case statement. Forgetting this will lead to fall-through behavior, where subsequent blocks might also execute.Advanced case Statement Features
Beyond simple string matching, Bash case statements support several advanced features that enhance their utility. These include using wildcards for pattern matching, combining multiple patterns, and handling ranges of values. Understanding these features allows for more robust and flexible script design.
Wildcard Matching
Bash case statements support standard shell wildcards (*, ?, []) for pattern matching. This is incredibly powerful for matching flexible inputs.
#!/bin/bash
read -p "Enter a filename: " filename
case "$filename" in
*.txt)
echo "This is a text file."
;;
*.{jpg,png,gif})
echo "This is an image file."
;;
[0-9]*)
echo "Filename starts with a number."
;;
*)
echo "Unknown file type or pattern."
;;
esac
Using wildcards and pattern lists in a case statement.
Multiple Patterns and Ranges
You can specify multiple patterns for a single block of commands by separating them with a | (pipe) character. While case doesn't directly support numeric ranges like 1..10, you can achieve similar functionality using wildcards or by nesting if statements within case blocks for more complex range checks.
#!/bin/bash
read -p "Enter a single digit number (0-9): " digit
case "$digit" in
0|1|2|3)
echo "You entered a low digit."
;;
[4-7])
echo "You entered a mid-range digit."
;;
8|9)
echo "You entered a high digit."
;;
*)
echo "Invalid input. Please enter a single digit."
;;
esac
Handling multiple patterns and simple ranges in a case statement.
if statement within a case block, or to perform the range check before entering the case statement if the case is primarily for other types of matching.Practical Applications and Best Practices
Case statements are incredibly versatile. They are commonly used for parsing command-line arguments, creating interactive menus, and implementing state machines in scripts. When writing case statements, consider the following best practices:
1. Always Quote the Variable
Always quote the variable being evaluated (e.g., case "$variable" in ...) to prevent issues with word splitting or globbing if the variable contains spaces or special characters.
2. Use a Default Catch-all
Include a *) default case to handle unexpected inputs. This makes your script more robust and user-friendly by providing feedback for invalid options.
3. Order Patterns Carefully
Patterns are evaluated in the order they appear. If a more general pattern could match before a more specific one, ensure the specific pattern is listed first to avoid unintended matches.
4. Keep Patterns Concise
While powerful, overly complex patterns can reduce readability. If a pattern becomes too intricate, consider pre-processing the input or using if statements for parts of the logic.