Unix
In this tutorial we will learn about Case conditional statement in Shell Programming.
Similar to the if statement we use the case statement to make decisions and execute a block of code based on some match.
case word in pattern1) # block of code for pattern1 ;; pattern2) # block of code for pattern2 ;; *) # default block ;; esac
Where, word is some value that is matched with the pattern1, pattern2 and so on.
word
pattern1
pattern2
If the word matches any pattern then the block of code belonging to that pattern is executed.
The ;; marks the end of the block and takes us out of the case.
;;
The *) represents the default pattern. If no match is found then the code in the default pattern is executed.
*)
The default pattern *) is optional and can be omitted.
The esac (reverse of case) marks the end of the case statement.
esac
In the following example we will print the number.
#!/bin/sh # take a number from user echo "Enter number:" read num case $num in 1) echo "It's one!" ;; 2) echo "It's two!" ;; 3) echo "It's three!" ;; *) echo "It's something else!" ;; esac echo "End of script."
Output:
$ sh num.sh Enter number: 10 It's something else! End of script. $ sh num.sh Enter number: 2 It's two! End of script.
In the following example we will take user name and time of the day as input and display some greetings message.
#!/bin/sh # take user name echo "Enter your name:" read name # take time of the day echo "Enter time of the day [Morning/Afternoon/Evening/Night]:" read daytime case $daytime in "Morning") echo "Good Morning $name" ;; "Afternoon") echo "Good Afternoon $name" ;; "Evening") echo "Good Evening $name" ;; "Night") echo "Good Night $name" ;; esac echo "End of script."
$ sh greetings.sh Enter your name: Yusuf Shakeel Enter time of the day [Morning/Afternoon/Evening/Night]: Morning Good Morning Yusuf Shakeel End of script. $ sh greetings.sh Enter your name: Yusuf Shakeel Enter time of the day [Morning/Afternoon/Evening/Night]: End of script.
In the second run we don't get any greetings message because the time of the day was not provided and the default pattern *) is not present in the case statement to handle such scenario.
So, we can modify the above code to handle such scenario by including the *) default pattern.
#!/bin/sh # take user name echo "Enter your name:" read name # take time of the day echo "Enter time of the day [Morning/Afternoon/Evening/Night]:" read daytime case $daytime in "Morning") echo "Good Morning $name" ;; "Afternoon") echo "Good Afternoon $name" ;; "Evening") echo "Good Evening $name" ;; "Night") echo "Good Night $name" ;; *) echo "Time of the day missing!" ;; esac echo "End of script."
$ sh greetings-1.sh Enter your name: Yusuf Shakeel Enter time of the day [Morning/Afternoon/Evening/Night]: Time of the day missing! End of script.