Often, one wants to perform specific actions on specific values of a variable. This is an example of such a program:
#!/bin/sh
case $# in
0) echo no parameters;;
1) echo only one parameter.
echo put commands to be executed here.;;
*) echo more than one parameter.
echo enter code here.;;
esac
exit 0
Wildcards can be used as items within the case statement. Hence * means ``anything matches".
Note the use of teh double semicolons. These are always required to terminate case pattern statements.
A much more powerful case example would be:
while :
do
echo "Would you like to continue? \c"
read ANS
case $ANS in
[yY] | [yY][eE][sS]) echo "Fine, then we'll continue."
break
;;
[nN] | [nN][oO]) echo "We shall now stop."
exit
;;
*) echo "You must enter a yes or no verdict!"
esac
done
echo "\nWe are now out of the while loop."
The example shows a number of tricks sometimes used during shell programming. The first is the use of an infinite while loop by using the : operator instead of a test operator. The : always returns a successful result (represented by a return code of 0). (In general, teh test operator is actually not needed - but is almost always used - to control loops. As test always returns 0 for a successful comparison and 1 for a non-successful comparison, it is easy to use. In reality, any appropriate UNIX command could be used to control the loops. The loop would then be entered if a return code of 0 were returned by the command.)
The second trick is done with the use of the break command. When break is encountered, the execution flow branches to the end of the outermost loop. In this case, the while loop.
Finally, the content of ANS is compared with a number of pattern matching sequences. Those pattern matching sequences actually replace a large number of if statements. In our case, the statement
[Yy] | [Yy][Ee][Ss] )would match Y, y, YES, YEs, Yes, yES, yEs, yeS, YeS and yes. The vertical bar | is an OR sign.
In fact, all shell metacharacters are allowed in forming a pattern match string. For example:
[a-z]* )would match any string beginning with a lower case character.