Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 3: Shells (bash) structured Language Constructs | ||
|
case $variable-name in pattern1) command ... .. command;; pattern2) command ... .. command;; patternN) command ... .. command;; *) command ... .. command;; esac
The $variable-name is compared against the patterns until a match is found. The shell then executes all the statements up to the two semicolons that are next to each other. The default is *) and its executed if no match is found. For e.g. write script as follows:
$ cat > car
|
Save it by pressing CTRL+D and run it as follows:
$ chmod +x car
$ car van
$ car car
$ car Maruti-800
First script will check, that if $1(first command line argument) is given or not, if NOT given set value of rental variable to "*** Unknown vehicle ***",if command line arg is supplied/given set value of rental variable to given value (command line arg). The $rental is compared against the patterns until a match is found.
For first test run its match with van and it will show output "For van Rs.10 per k/m."
For second test run it print, "For car Rs.20 per k/m".
And for last run, there is no match for Maruti-800, hence default i.e. *) is executed and it prints, "Sorry, I can not gat a Maruti-800 for you".
Note that esac is always required to indicate end of case statement.
See the one more example of case statement in chapter 4 of section shift command.
| ||
while loop | How to de-bug the shell script? |