To see the real power of case statements, we can look at examples involving pattern matching, multiple conditions, and system tasks.
Here are three complex examples:
1. The "File Organizer" (Pattern Matching)
This example uses wildcards (*) to determine what to do with different file types.
#!/bin/bash
FILE=$1
case "$FILE" in
*.jpg | *.png | *.gif)
echo "$FILE is an image file."
;;
*.mp3 | *.wav)
echo "$FILE is an audio file."
;;
*.sh)
echo "$FILE is a shell script."
;;
*)
echo "Unknown file type: $FILE"
;;
esac
Key Feature: The | (pipe) allows one block of code to handle multiple file extensions.
2. The "Smart Input" (Character Classes)
You can use case to validate the type of data entered by a user.
#!/bin/bash
read -p "Enter a single character: " DATA
case "$DATA" in
[0-9])
echo "You entered a digit."
;;
[a-z])
echo "You entered a lowercase letter."
;;
[A-Z])
echo "You entered an uppercase letter."
;;
?)
echo "You entered a special symbol."
;;
*)
echo "You entered more than one character or nothing at all."
;;
esac
Key Feature: [a-z] and [0-9] represent ranges. The single ? matches exactly one character that isn't a letter or digit.
3. The "System Menu" (Infinite Loop + Case)
This is a standard way to build a command-line interface (CLI) for system administration.
#!/bin/bash
while true; do
echo "--- SYSTEM MENU ---"
echo "1. Show Disk Usage"
echo "2. Show Uptime"
echo "3. Exit"
read -p "Choose an option [1-3]: " choice
case $choice in
1)
df -h | head -n 5
;;
2)
uptime -p
;;
3)
echo "Goodbye!"
exit 0
;;
*)
echo "Invalid choice, try again."
;;
esac
echo ""
done
Key Feature: Combining case with a while true loop creates an interactive tool that keeps running until the user chooses "Exit".
Why these are better than if-elif:
- Cleaner Syntax: Handling
*.jpg | *.pngin anifstatement would require long strings of[[ $FILE == *.jpg ]] || [[ $FILE == *.png ]]. - Scalability: You can easily add 10 more file types to Example 1 without making the code hard to read.
Which of these styles would be most useful for your own project?