Syntax and Structure of Case Statements
The basic syntax for a case statement in Bash is as follows:
case expression in
pattern1)
commands
;;
pattern2)
commands
;;
...
patternN)
commands
;;
*)
default commands
;;
esac
Let's break down the different components of this structure:
expression
The expression is the value or variable that you want to evaluate. This can be a string, a number, or even the output of a command.
pattern
The pattern is the value or pattern that you want to match against the expression. You can use simple values, wildcards (such as *
and ?
), or even regular expressions to create more complex patterns.
commands
The commands are the actions that you want to perform if the corresponding pattern matches the expression.
;;
The double semicolon ;;
is used to terminate each case statement block.
*)
The *
pattern is a catch-all that will match any value that doesn't match the previous patterns. This is often used as a default case to handle any unmatched scenarios.
Here's an example of a case statement that checks the value of a variable $COLOR
and performs different actions based on the value:
#!/bin/bash
COLOR="red"
case $COLOR in
red)
echo "The color is red."
;;
blue)
echo "The color is blue."
;;
green)
echo "The color is green."
;;
*)
echo "The color is not red, blue, or green."
;;
esac
This script will output The color is red.
when run, as the value of $COLOR
is set to "red"
.