What is Case?

case…esac Conditional construct statement- It is used to check for multiple conditions for a decision making process in a shell script.

  • It is better alternative for Ladder if-elif conditional construct statement.
  • It evaluates a value of the variable and compares it with case specified by the user.
  • The commands under a particular case value must be followed by a pair of semicolon (;;) to delimit it from set of commands under the next case value.

Syntax


		
case $variable_name in
			case1_pattern)
				<commands>
			;;
			case2_pattern)
				<commands>
			;;
			case3_pattern)
				<commands>
			;;
			.
			.
			*)						//default_case
				<commands>
			;;
			esac

		
  • $variable_name i.e. variable value is matched with the case pattern and the commands under that case upto ;; are executed.
  • *) is the default case and is evaluated is no case matches with variable value.

Example of Case in Shell Scripting


		
#!/bin/bash
read –p “Enter a character:”  char
case $char in 
[a-z])
echo “ You have entered a lower case alphabet”
;;
[A-Z])
echo “ You have entered an upper case alphabet”
;;

[0-9])
echo “ You have entered a digit”
;;

?)
echo “ You have entered some other special character”
;;

*)
echo “ You have entered more than one character”
;;
esac