| |
 |
|
Oracle Tips by Burleson |
The case statement
Instead of nesting many if-then-else or if-then-else-then
statements, another alternative is to use the case statement. The
case statement allows you to perform a different set of commands
depending upon the value associated with a string variable.
Using the case statement
echo -n " What type of pet do you
have (dog, cat, etc.)? "
read pet
echo " "
case $pet in
dog) echo " So you have a dog ..."
echo " That's nice, so do I."
echo " My dog's name is Fido.";;
cat) echo " So you have a cat ..."
echo " I'm allergic to cats!";;
fish) echo " So you have fish ..."
echo " Can't take them for a walk .. ha, ha.";;
ferret) echo " Ferrets are cool!";;
*) echo " A $pet ... that's a funny pet";;
esac
echo " "
The case example script above asks the user what kind of pet they
have and then provides different responses depending upon the type
of pet answered. It looks for answers of “dog”, “cat”, “fish”,
“ferret”, and “*”. The asterisk (*) matches any other answer
supplied by the user. When a match is found by the case statement,
all commands are executed until a double semi-colon (;;) is
encountered.
When the example above is entered and saved to a file (we’ll learn
this in the next chapter) called whatpet.ksh, we can run it as shown
below:
Running the case script
$ ./whatpet.ksh
What type of pet do you have (dog, cat, etc.)? moose
A moose ... that's a funny pet
$ ./whatpet.ksh
What type of pet do you have (dog, cat, etc.)? dog
So you have a dog ...
That's nice, so do I.
My dog's name is Fido.
The above book excerpt is from:
Easy Linux
Commands
Working Examples of Linux Command Syntax
ISBN:
0-9759135-0-6
Terry Clark
http://www.rampant-books.com/book_2005_1_linux_commands.htm |