In shell scripting, the case statement is a powerful construct that enables executing different commands based on patterns. Here, I'll demonstrate with an example how to use the case statement for pattern matching.
Suppose we need to create a script that outputs characteristics of a season based on user input (e.g., spring, summer, autumn, winter).
bash#!/bin/bash echo "Please enter the season name (spring, summer, autumn, winter):" read season case $season in spring) echo "Spring: Flowers bloom" ;; summer) echo "Summer: Hot weather" ;; autumn) echo "Autumn: Leaves fall" ;; winter) echo "Winter: Cold temperatures" ;; *) echo "Invalid input. Please enter a valid season name (spring, summer, autumn, winter)." ;; esac
How to Interpret This Script?
-
Reading User Input: Use the
readcommand to capture the user's input for the season name and store it in the variableseason. -
Using the
caseStatement for Pattern Matching:case $season ininitiates acasestatement, where$seasonis the variable to match against.- For each pattern (e.g.,
spring), it is followed by), then the command to execute (e.g.,echo "Spring: Flowers bloom"), and the command block concludes with;;. - If the input doesn't match any defined pattern, the
*pattern executes. This serves as the 'default' or 'other' case for inputs that don't align with predefined patterns.
Conclusion
This approach enhances script readability and maintainability. With the case statement, we can execute distinct commands based on specific inputs, making the script more flexible and robust. For handling choices or conditional branches, the case statement is an excellent choice.