How to use the command "case" in Bash (with examples)
The “case” command in Bash is a built-in construct that allows for creating multi-choice conditional statements. It can be used to match a variable against string literals and decide which command to run based on the match.
Use case 1: Match a variable against string literals to decide which command to run
Code:
case $tocount in
words) wc -w README;;
lines) wc -l README;;
esac
Motivation: This use case is useful when you want to execute different commands based on the value of a variable. Using the “case” construct allows you to simplify the conditional statement and avoid multiple nested if-else statements.
Explanation:
- “case”: The keyword to start the “case” construct.
- “$tocount”: The variable to match against the string literals.
- “in”: Separates the variable from the string literals.
- “words)”: The first string literal to match. In this case, if the value of $tocount is “words”, the following command “wc -w README” will be executed.
- “lines)”: The second string literal to match. If the value of $tocount is “lines”, the command “wc -l README” will be executed.
- “;;”: Terminates each command executed for a matched string literal.
- “esac”: The keyword to end the “case” construct.
Example output: If the value of $tocount is “words”, the command “wc -w README” will be executed and will output the number of words in the “README” file.
Use case 2: Combine patterns with |, use * as a fallback pattern
Code:
case $tocount in
[wW]|words) wc -w README;;
[lL]|lines) wc -l README;;
*) echo "what?";;
esac
Motivation: This use case builds upon the previous one by allowing you to match multiple patterns for a variable and providing a fallback pattern.
Explanation:
- [wW]|words): This pattern matches the string literals “w” or “W” or “words”. If the value of $tocount matches any of these patterns, the command “wc -w README” will be executed.
- [lL]|lines): This pattern matches the string literals “l” or “L” or “lines”. If the value of $tocount matches any of these patterns, the command “wc -l README” will be executed.
- : The asterisk () acts as a fallback pattern and matches any other value that does not match the previous patterns.
- echo “what?”: This command is executed if the value of $tocount does not match any of the previous patterns.
Example output: If the value of $tocount is “L”, the command “wc -l README” will be executed and will output the number of lines in the “README” file.
If the value of $tocount is “characters”, the fallback pattern will match and the command “echo “what?”” will be executed, outputting “what?”.
Conclusion:
The “case” command in Bash is a powerful tool for creating multi-choice conditional statements. It allows you to simplify conditional logic and execute different commands based on the value of a variable. By combining patterns and using fallback patterns, you can create even more flexible and comprehensive conditional statements.