Switch (Case) Statement in Bash
The case
statement in Bash is a conditional construct that simplifies checking multiple conditions. It’s often used when comparing a variable or expression against multiple patterns and executing corresponding commands.
Why Use a Case Statement?
- Readability: Easier to understand compared to nested
if-elif
statements. - Efficiency: Suitable for matching multiple cases quickly.
- Flexibility: Supports pattern matching with wildcards and ranges.
Syntax
Key Points:
variable
is the value to evaluate.pattern
is the condition to match. It can include wildcards (*
,?
) or ranges ([a-z]
).;;
marks the end of a block of commands.*
serves as the default case (executed if no other pattern matches).esac
marks the end of thecase
block.
Basic Example: Menu Selection
Output (if user inputs 1
):
Advanced Example: File Type Checker
Output (if user inputs image.jpg
):
Example: Using Ranges
Case Statement with Command Substitution
You can evaluate the result of a command using case
:
Handling Multiple Patterns
You can combine patterns using |
(logical OR):
Output (if user inputs apple
):
Using Functions with Case Statements
You can pair functions with case
to keep your script modular:
Conclusion
The case
statement in Bash is a powerful tool for handling multiple conditions elegantly. It’s versatile, supports pattern matching, and is much cleaner than using multiple if-elif
statements. Whether you're writing a menu-driven script, checking file types, or handling user input, the case
statement is your go-to solution.
Let me know if you'd like additional examples or adjustments!