bash math operation code example
Example 1: how to do math in bash
expr 1 - 1
0
expr 1 + 1
2
myvar=$(expr 1 + 1)
echo $myvar
2
expr $myvar + 1
3
expr $myvar / 3
0
expr $myvar \* 3
6
Example 2: arithmetic operation in bash
#!/bin/bash
x=5
y=10
ans=$(( x + y ))
echo "$x + $y = $ans"
Example 3: how to perform mathematical operations in shell script
#!/bin/sh
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi