Bash Scripting – Case Statement
Often, you’ll find yourself trying to evaluate a variable’s value, looking for a specific value within a set of possible values. In this scenario, you end up having to write a lengthy if-then-else statement, like this:
$ cat test25.sh
#!/bin/bash
# looking for a possible value
#
if [ $USER = “rich” ]
then
echo “Welcome $USER”
echo “Please enjoy your visit”
elif [ $USER = “barbara” ]
then
echo “Welcome $USER”
echo “Please enjoy your visit”
elif [ $USER = “testing” ]
then
echo “Special testing account”
elif [ $USER = “jessica” ]
then
echo “Do not forget to logout when you're done”
else
echo “Sorry, you are not allowed here”
fi
$
$ ./test25.sh
Welcome rich
Please enjoy your visit
$
The elif statements continue the if-then checking, looking for a specific value for the single comparison variable.
Instead of having to write all the elif statements to continue checking the same variable value, you can use the case command. The casecommand checks multiple values of a single variable in a list-oriented format:
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
The case command compares the variable specified against the different patterns. If the variable matches the pattern, the shell executes the commands specified for the pattern. You can list more than one pattern on a line, using the bar operator to separate each pattern. The asterisk symbol is the catch-all for values that don’t match any of the listed patterns. Here’s an example of converting the if-then-else program to using the case command:
$ cat test26.sh
#!/bin/bash
# using the case command
#
case $USER in
rich | barbara)
echo “Welcome, $USER”
echo “Please enjoy your visit”;;
testing)
echo “Special testing account”;;
jessica)
echo “Do not forget to log off when you're done”;;
*)
echo “Sorry, you are not allowed here”;;
esac
$
$ ./test26.sh
Welcome, rich
Please enjoy your visit
$
The case command provides a much cleaner way of specifying the various options for each possible variable value.