The case statement
The case statement enables to compare a pattern with various other patterns and execute a block of code if a match is found. The shell case statement is associatively powerful than the switch statement in C and the case statement in Pascal or. The motive for such a condition is that it is possible to compare strings in the shell case statement by using wildcard characters.
Syntax
case string1 in
str1)
commands;;
str2)
commands;;
*)
commands;;
esac
Practice 1
The given shell program will create and show and delete a file by using case statement
# vi casefile
echo -e "Enter the filename :\\c"
read fname
echo -e "Enter the selection (1-create;2-display;3-delete):\\c"
read choice
case $choice in
1) cat > $fname;;
2) cat $fname;;
3) rm $fname;;
*) echo "Select the option among [1-3] "
break;
esac
# sh casefile
Enter the filename: sivam
Enter the selection (1-create;2-display;3-delete):1
Using case statement this is a demo to create a file
To display the file
^d
# sh casefile
Enter the filename: sivam
Enter the selection (1-create;2-display;3-delete):2
Using case statement this is a demo to create a file
To display the file
# sh casefile
Enter the filename: sivam
Enter the selection (1-create;2-display;3-delete):4
Select the option among [1-3]
The given program gives 3 selections from 1 to 3. It Depending on the value in which is chosen the corresponding command is executed. If any other value is selected, it will show "Select the option among [1-3]".