The case statement in shell scripting provides a way to perform conditional branching based on the value of a variable or an expression. It’s similar to a series of if-elif-else statements, but it can be more concise and readable in certain situations.
Here’s a detailed breakdown of the case statement:
Syntax:
case expression in
pattern1)
# Code to execute if expression matches pattern1
;;
pattern2)
# Code to execute if expression matches pattern2
;;
...
*)
# Default code to execute if none of the patterns match
;;
esaccase: Indicates the start of thecasestatement.expression: This is the value that you want to compare against the patterns. It can be a variable, a command substitution, or any expression that yields a result.in: Marks the beginning of the pattern matching section.pattern1),pattern2), …: These are the patterns that are compared against the expression. If a pattern matches the expression, the corresponding block of code is executed. Patterns are typically strings, but they can also be regular expressions.;;: This signals the end of a block of code for a particular pattern. It’s important to include this after each block of code to prevent “fall-through” (i.e., executing code for subsequent patterns if a match is found).*): The asterisk (*) is a wildcard pattern that matches anything. The default case is executed if none of the previous patterns match.esac: This marks the end of thecasestatement.
Example:
#!/bin/bash
fruit="apple"
case $fruit in
"apple")
echo "It's an apple."
;;
"banana")
echo "It's a banana."
;;
"cherry")
echo "It's a cherry."
;;
*)
echo "It's something else."
;;
esacIn this example, the value of the variable fruit is compared against different fruit names using the case statement. If a match is found, the corresponding message is printed. Otherwise, the default case (“It’s something else.”) is executed.
case statements are useful when you have a series of conditions to check against a single variable. They can make your code more readable and organised compared to a series of if-elif-else statements, especially when dealing with multiple cases.
