Bash, the beloved scripting language for Linux and Unix systems, offers a powerful tool for decision-making: the case statement. Let’s unravel how this feature can elevate your scripts’ efficiency and readability.
What is a Bash Case Statement?
Think of a case
statement as an elegant way to compare a variable’s value against multiple possibilities. It’s like having a series of “if-else” checks, but much neater.
How It Works
- Expression: The variable you want to evaluate.
- Patterns: A list of potential values the variable might hold. These patterns often resemble file globbing patterns (think
*.txt
). - Statements: The actions to execute if a pattern matches the expression.
Syntax Breakdown
case "$variable" in
pattern1)
statements ;;
pattern2)
statements ;;
*)
statements ;; # Default case (catch-all)
esac
Important Notes:
- Order Matters: Patterns are checked in sequence, so put your most specific matches first.
- Double Semicolons: These
;;
signify the end of statements for each pattern. - Wildcards: The
*
acts as a wildcard, matching any sequence of characters.
Examples
Example 1: Yes or No Response
read -p "Are you sure? (yes/no) " ans
case "$ans" in
[Yy]|[Yy][Ee][Ss])
echo "Will do!" ;;
[Nn]|[Nn][Oo])
echo "Oops!" ;;
*)
echo "Invalid input. Please enter yes or no." ;;
esac
Example 2: File Type Identifier
filename="document.txt"
case "$filename" in
*.txt)
echo "Text file" ;;
*.jpg|*.jpeg|*.png)
echo "Image file" ;;
*)
echo "Unknown file type" ;;
esac
Output:
Text file
Example 3: Numeric Comparison
number=5
case "$number" in
[0-4])
echo "Small number" ;;
5)
echo "Bingo! It's five!" ;;
[6-9])
echo "Larger number" ;;
*)
echo "Not a number between 0 and 9" ;;
esac
Output:
Bingo! It's five!
Why Use Case Statements?
- Enhanced Readability: Compared to a long string of
if-else
statements,case
is more organized and visually appealing. - Efficient Logic: When dealing with multiple options,
case
statements often execute faster.