Case Control in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Case Control in Shell Script

Share This

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/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
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
CBasic alculator using `expr`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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";;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
basic_calculator_expr

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.