10 Case Statement - kumar159man/MyShellLearning GitHub Wiki

Switch Case in bash scripting

Let's write a shell script for calculator operation

#!/usr/bin/bash
read -p "Enter first number" num1
read -p "Enter second number" num2
echo "****************Menu for calculator********************"
echo "For Addition enter +"
echo "For Substraction enter -"
echo "For Multiplication enter x"
echo "For Division enter /"
echo "*******************************************************"
read -p "Enter the your option" opt
case $opt in
    +)
        echo "Addition of $num1 and $num2 is $((num1+num2))"
        ;;
    -)
        echo "Substraction of $num1 and $num2 is $((num1-num2))"
        ;;
    x)
        echo "Multiplication of $num1 and $num2 is $((num1*num2))"
        ;;
    /)
        echo "Division of $num1 and $num2 is $(bc<<< "scale=2; $num1/$num2")"
        ;;
    *)
        echo "Invalid Choice"
        ;;
esac

Let's write another shell script to demonstrate regular expression in case statement

#!/usr/bin/bash
read -p "Enter a character" ch
case $ch in
     [0-9])
            echo "The character entered is a digit"
            ;;
     [a-z])
            echo "The character entered is a lower case alphabet"
            ;;
     [A-Z])
            echo "The character entered is an upper case alphabet"
            ;;
         *)
            echo "The character entered is some kind of symnol"
esac