Interview Questions

Shell Script – Arithmetic Operations

In this article let us see how to perform Shell script arithmetic operations.

In the Shell command line, in order to perform the arithmetic operation, we need to execute the below command,
$ expr 1 + 4

The same arithmetic operation can be performed in the Shell script as follows,

ArithmeticOperation.sh

echo "Arithmetic operations"
x=2
y=1
sum=`expr ${x} + ${y}`
diff=`expr ${x} - ${y}`
multiply=`expr ${x} \* ${y}` # For multiplication, use \* since * is a wild card character
division=`expr ${x} / ${y}`
modulus=`expr ${x} % ${y}`

echo "x = ${x}"
echo "y = ${y}"
echo "Sum = ${sum}"
echo "Diff = ${diff}"
echo "Multiply = ${multiply}"
echo "Division = ${division}"
echo "Modulus = ${modulus}"

Output

$ sh ArithmeticOperation.sh
Arithmetic operations
x = 2
y = 1
Sum = 3
Diff = 1
Multiply = 2
Division = 2
Modulus = 0