case..esac..in Linux Shell Script
By: Dorris
The case statement is good alternative to Multilevel if-then-else-fi statement. It enable you to match several values against one variable. Its easier to read and write.Syntax:
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
#
# if no vehicle name is given
# i.e. -z $1 is defined and it is NULL
#
# if no command line arg
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as rental
rental=$1
fi
case $rental in
"car") echo "For $rental Rs.20 per
k/m";;
"van") echo "For $rental Rs.10 per
k/m";;
"jeep") echo "For $rental Rs.5 per
k/m";;
"bicycle") echo "For $rental 20 paisa
per k/m";;
*) echo "Sorry, I can not gat a $rental for
you";;
esac
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.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
smskannel SMS gateway run in background
Running jar files in background in ssh window
Can't locate ExtUtils/MakeMaker.pm in @INC ...
Could not open '': No such file or directory at lib/ExtUtils/MM_Unix.pm line 2697
make: Nothing to be done for `all'.
How to burn your CD / DVD ISO image using Nero Burning ROM (Ahead Software) on Windows
How to burn your CD / DVD ISO image using Media Creator (Adaptec/Roxio) on Windows
How to burn your CD / DVD ISO image using Nero Express (Ahead Software) on Windows
How to burn your CD / DVD ISO image using NISO Recorder V2 Power Toy on Windows
Compiling and Installing software from source in Linux