Case Statements (Switch Statements)
- It is an example of selection statement and alternative option for multiple if..elif..else statements
- It is equivalent to switch case statements in c language
- It is used to execute several statements based on the value of expression
- This is done by using the reserved word case
Usage
- It is mainly used to create a menu driven program in shell scripting.
Syntax
case <variable> in
Pattern 1)
Commands / statements
;;
Pattern 2)
Commands / statements
;;
…
*) ;;
easc
Where,
- *) indicates the default section like c language
- ;; represents the break keyword in case statements.
EXAMPLE SCRIPT
V. MENU DRIVEN PROGRAM
1. SOURCE CODE
while [ true ]
do
echo “————————————-“
echo “\t\t Menu Program”
echo “————————————-“
echo “1. View Files \t 2.Date”
echo “3. Users List \t4.Calendar”
echo “5. Exit”
echo “\tEnter ur choice : “
read ch
#switch case
case $ch in
1) ls;;
2) date;;
3) w;;
4) cal;;
5) exit;;
esac
# read choice from user for continuation of program execution
echo “Do you want to continue : Press Yes/No”
read ch
if [ $ch = “yes” ] || [ $ch = “Yes” ] || [ $ch = “YES” ]
then
continue
else
exit
fi
done
NOTE
- It is important to note that the single equal operator = is used for string comparison and the symbol –eq or == is used for number comparison in the shell program.
2. OUTPUT
2.1 MENU OPTIONS
2.1 MENU OPTIONS – (Continue)
Related Posts
1. Arrays in Bash Script
2. For Loop in Bash Script
3. Strings in Bash Script (Shell Script)
4. File Test Operators in Bash Script