Tuesday, April 14, 2009

Case statement in shell script

In stead of writing if -elif -else statement case statement can be used which makes the code more readable and easily understandable as well as makes coder to manage code better. The syntax of the case statement is,

case $variable in
pattern1) .......
command;;
pattern2) .......
command;;
patternN) .......
command;;
*) .......
command;;
esac

The $variable is compared against the patterns until a match is found. If a pattern is found, shell will then executes all the statements up to the two semicolons(;;).
If no pattern is matched the default is *) command section is executed.

An example of case statement in shell script is shown below.

# cat case_test.sh
echo "1.Orange"
echo "2.Apple"
echo "3.Mango"
echo "4.Potato"
echo -n "Enter your choice : "
read choice
case $choice in
1)
echo "You chose Orange";;
2)
echo "You chose Apple";;
3)
echo "You chose Mango";;
4)
echo "You chose Potato";;
*)
echo "You didn't chose any";;
esac

# chmod +x case_test.sh

# ./case_test.sh
1.Orange
2.Apple
3.Mango
4.Potato
Enter your choice : 1
You chose Orange

# ./case_test.sh
1.Orange
2.Apple
3.Mango
4.Potato
Enter your choice : 89
You didn't chose any

You can easily check yes/no type user input using case statement in shell script. Below is my part of the installation script.

# cat case_yn.sh
echo -n "Do you want to continue? (y/n) "
read yesno
case $yesno in
Y|y)
echo "Continuing" ;;
[Yy][Ee][Ss])
echo "Continuing" ;;
N|n)
echo "Exiting"
exit;;
[Nn][Oo])
echo "Exiting"
exit ;;
*) echo "Invalid command"
esac

# ./case_yn.sh
Do you want to continue? (y/n) yes
Continuing

# ./case_yn.sh
Do you want to continue? (y/n) y
Continuing

# ./case_yn.sh
Do you want to continue? (y/n) no
Exiting

# ./case_yn.sh
Do you want to continue? (y/n) arju
Invalid command

Related Documents

No comments:

Post a Comment