In C programming language you have seen that switch-case is used to perform a set of operations based on some values. In a shell script, a similar type of logic can be implemented by using a case. In the following example, we have shown how the case works.
To run this script, we have to pass three arguments, such as 10 + 7.
Basic Calculator
#!/bin/bash
if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 is invalid operator
exit;;
esac
echo The result is $z
else
echo "Usage - $0 first_value operator second_value"
echo " Where, first_value and second_value are numeric values"
echo " and the operator is either +, -, x or /"
fi
CBasic alculator using `expr`
echo "Enter the first number"
read a
echo "Enter the second number"
read b
echo "Enter the operator:"
echo -e "Addition: +\nSubtraction: -\nMultiplication: x\nDivision: /"
read op
case $op in
+) c=`expr $a + $b`
echo "Sum of $a and $b is $c";;
-) c=`expr $a - $b`
echo "Difference of $a and $b is $c";;
x) c=`expr $a \* $b`
echo "Product of $a and $b is $c";;
/) c=`expr $a / $b`
echo "Division of $a and $b is $c";;
*) echo "Invalid Operator"
exit;;
esac
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.