The Case command
In a previous article, we looked at making commands within the script execute only if a given condition is true, using the if….else…fi construct. However, this construct can often become very clumsy when there are several possible conditions to be accounted for. Take the menu script example below:
clear
echo User Menu for $LOGNAME
echo Accounts......................1
echo Star Office...................2
echo Wages .........................3
echo Exit .............................4
echo
echo Please enter your choice 1,2,3 or 4
read menu_choice
if [ $menu_choice = 1 ]
then
accounts
elif [ $menu_choice = 2]
then
star
elif [ $menu_choice = 3 ]
then
wages
else
exit
fi
$0
Here we have four different conditions, all depending on the single variable $menu_choice. If we wanted to add more choices to the menu, it would become even more complex.
There is a better way of doing this, provided that all the conditions depend on the value of a single variable. This is to use the case construct.
clear
echo User Menu for $LOGNAME
echo Accounts......................1
echo Star Office...................2
echo Wages .........................3
echo Exit .............................4
echo
echo Please enter your choice 1,2,3 or 4
read menu_choice
case $menu_choice
in
1) accounts;;
2) star;;
3) wages;;
4) exit;;
*) echo $menu_choice is not a valid option;;
esac
$0
This new script does exactly the same as the old one, but it is much neater, and much easier to expand if more menu choices are added.
As with the if…fi construct, the syntax of the case…esac construct is very strict. It must begin with the word case followed by the name of the variable whose contents are to be examined. The word in must be placed on a separate line. The expected values must then be listed, each on a separate line followed immediately by the close bracket symbol. After the bracket, there is a space followed by one or more commands to be executed if the variable has this value. A double semi-colon terminates the list of commands.
The values to be matched may contain wild cards. Thus the *) matches to any value of menu_choice. Any value of menu_choice (e.g. 5 or 6) not previously matched will be seen as a match here. This then causes any value that is not between 1 and 4 to display the error message.