The case statement in shell scripting is a control structure that allows you to execute different blocks of code based on the value of a variable or expression. It is particularly useful for handling multiple conditions in a more organized and readable way compared to using multiple if statements.
Syntax:
case variable in
pattern1)
# Commands to execute if variable matches pattern1
;;
pattern2)
# Commands to execute if variable matches pattern2
;;
...
*)
# Commands to execute if no patterns match (default case)
;;
esac
Key Components:
- Variable: The variable or expression being evaluated.
- Patterns: Each pattern is checked against the value of the variable. If a match is found, the corresponding commands are executed.
- Commands: The commands that will run if the pattern matches.
- Double Semicolon (
;;): This marks the end of each case block. - Default Case (
*): This is executed if none of the specified patterns match the variable's value.
Example:
Here’s a simple example of a case statement that checks the value of a variable:
#!/bin/bash
echo "Enter a number (1-3): "
read number
case $number in
1)
echo "You entered One."
;;
2)
echo "You entered Two."
;;
3)
echo "You entered Three."
;;
*)
echo "Invalid input. Please enter a number between 1 and 3."
;;
esac
Advantages:
- Readability: The
casestatement makes the code cleaner and easier to read, especially when dealing with multiple conditions. - Efficiency: It can be more efficient than multiple
ifstatements, as it evaluates the variable against patterns in a single structure.
Use Cases:
- Menu selections
- Command-line argument parsing
- Handling different input types or values
The case statement is a powerful tool in shell scripting for managing multiple conditions effectively.
