Bash Case

Bash case command is similar to the switch statement of other programming languages. It is useful when you need to check the same variable value in elif statements.

Syntax: Bash case command

case variable in
pattern1)
   commands1;;
pattern2 | pattern3)
   commands2;;
*)
   commands3;;
esac

The value of a variable is matched against patterns if the value matches with any pattern then commands specified under that pattern is executed and all other commands are skipped.

If you want you can write more than one pattern on a single line by separating them with a bar operator.

Commands listed under asterisk symbol are executed only when there is no matching of patterns.

Example1: Check a given character is vowel or not using Bash case

#Bash script to check whether a goven character is vowel or not
echo -n "Enter a character: "
read -n 1 character
case $character in
"a" | "e" | "i" | "o" | "u")
   echo
   echo "It's a vowel.";;
*)
   echo
   echo "It's not a vowel.";;
esac

Output of the above program

Enter a character: a
It's a vowel.
Enter a character: q
It's not a vowel.

Example2: To build mini calculator using Bash case

#Bash script to build mini calculator
read -p "Enter first number: " firstNumber
read -p "Enter second number: " secondNumber
echo "What operation you want to perform"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read -p "Enter your choice(1-4): " choice
case $choice in
1)
  ans=$(( firstNumber + secondNumber ))
  echo "Addition of $firstNumber and $secondNumber is $ans";;
2)
  ans=$(( firstNumber - secondNumber ))
  echo "Subtraction of $firstNumber and $secondNumber is $ans";;
3)
  ans=$(( firstNumber * secondNumber ))
  echo "Multiplication of $firstNumber and $secondNumber is $ans";;
4)
  ans=$(( firstNumber / secondNumber ))
  echo "Division of $firstNumber and $secondNumber is $ans";;
esac

Output of the above program

Enter first number: 45
Enter second number: 5
What operation you want to perform
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice(1-4): 2
Subtraction of 45 and 5 is 40