That is an excellent question! While if-elif-else and case can often achieve the same result, case is generally considered better in the following scenarios:
1. Readability with Multiple Matches
When you are checking a single variable against many possible values (like a menu selection or command-line flags), case is much cleaner and easier to read.
- if-elif-else version:
if [ "$choice" == "1" ]; then add elif [ "$choice" == "2" ]; then subtract elif [ "$choice" == "3" ]; then multiply else echo "Invalid" fi - case version:
case $choice in 1) add ;; 2) subtract ;; 3) multiply ;; *) echo "Invalid" ;; esac
2. Pattern Matching (Wildcards)
case supports glob patterns (like *, ?, and []), making it very powerful for matching strings without using complex regular expressions.
case $filename in
*.txt) echo "This is a text file" ;;
*.jpg|*.png) echo "This is an image" ;;
[0-9]*) echo "This file starts with a number" ;;
*) echo "Unknown format" ;;
esac
3. Handling Multiple Conditions for one Action
In a case statement, you can use the pipe symbol | to mean "OR". This allows multiple patterns to trigger the same block of code without repeating your logic.
case $answer in
[yY]|[yY][eE][sS])
echo "You agreed!"
;;
[nN]*)
echo "You declined."
;;
esac
Summary: Use case when...
- You are evaluating one specific variable.
- You have many constant values to check against.
- You want to use simple pattern matching (like checking file extensions).
- You want to group multiple values together to trigger the same action.
Use if, however, when you need to compare different variables or perform complex math logic (like if [ $a -gt $b ] && [ $c -lt $d ]).