乐闻世界logo
搜索文章和话题

How do you use the case statement to match patterns in shell scripting?

1个答案

1

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?

  1. Reading User Input: Use the read command to capture the user's input for the season name and store it in the variable season.

  2. Using the case Statement for Pattern Matching:

    • case $season in initiates a case statement, where $season is 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.

2024年8月14日 17:33 回复

你的答案