Case in ShellScript
You can use multiple if..elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements.
The case statement saves going through a whole set of if .. then .. else statements. Its syntax is really quite simple:
Example:
#!/bin/bash
action=${1,,}
# start,stop,restart,reload
case ${action} in
start)
echo "going to start"
echo "actionone two"
;;
stop)
echo "going to stop"
;;
reload)
echo "going to reload"
;;
restart)
echo "going to restart"
;;
*)
echo "please enter correct command line args."
esac
Let's run the above program with one command line argument.
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement.sh START
going to start
actionone two
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement.sh start
going to start
actionone two
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement.sh stop
going to stop
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement.sh sToP
going to stop
Case Statement with Regex
Example
read -p "enter y or n: " ANSWER
case "$ANSWER" in
[Yy] | [Yy][Ee][Ss])
echo "you answer yes"
;;
[Nn] | [Nn][Oo])
echo "you answer no"
;;
*)
echo "Invalid Answer"
;;
exit
esac
output
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casethree.sh
enter y or n: y
you answer yes
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casethree.sh
enter y or n: ye
Invalid Answer
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casethree.sh
enter y or n: yes
you answer yes
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casethree.sh
enter y or n: n
you answer no
Example-2
#!/bin/bash
read -p "enter y or n" answer
case ${answer,,} in
[y]*)
echo "you enter Yes"
;;
[n]* )
echo "you enter no"
;;
*)
echo "Invalid Anser"
;;
esac
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement-2.sh
enter y or ny
you enter Yes
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./casestatement-2.sh
enter y or nyeeeeeee
you enter Yes