Shell Scripting Tutorial: Shell script Arithmetic Operations

In this chapter we shall look at how to perform various arithmetic operations.

Arithmetic addition.

Simple way to add two numbers is given below:

#!/bin/bash

echo 1+2

Output:

1+2

This is not the output we had expected. Point to be noted here is, echo command will output whatever is given to it as input.
Hence we need to do any arithmetic separately as shown below:

I have taken 2 numbers, and will perform arithmetic operations:

To perform any arithmetic operations, you need to include them inside double brackets. Then you need to add “$” symbol, to compute the arithmetic operations.

#!/bin/bash
num_1=20
num_2=30

echo $(( num_1 + num_2 ))
echo $(( num_1 - num_2 ))
echo $(( num_1 / num_2 ))
echo $(( num_1 * num_2 ))

Output:

50
-10
0
600

Instead of using double brackets we can also use “expr” keyword to perform the operations. But here we need to give single bracket.

Note: When we use “expr” multiplication symbol “*” is not escaped. Hence we need to escape multiplication symbol like “\*”.

#!/bin/bash
num_1=20
num_2=30

echo $(expr $num_1 + $num_2 )
echo $(expr $num_1 - $num_2 )
echo $(expr $num_1 \* $num_2 )
echo $(expr $num_1 / $num_2 )

Output:

50
-10
600
0

Performing operations on floating or decimal numbers.

By default, the above 2 methods will not operate on decimal numbers.

To perform operations on floating point we need to use “bc” tool. “bc” stands for basic calculator.

We give the input to “bc” with the help of pipe “|” as shown below.

Note: “bc” tool will work correctly for all the operations, except for division. For division we need to append with “scale” keyword followed by number of decimal places needed. For example, we need decimal place upto 3 numbers then we can specify “scale=3;”

Example:

#!/bin/bash
num_1=1.5
num_2=2.5
 
echo "$num_1 + $num_2" |bc
echo "$num_1 - $num_2" |bc
echo "scale=2;$num_1/$num_2" |bc
echo "$num_1 * $num_2" |bc

Output:

4.0
-1.0
.60
3.7

Performing complex math operations:

To perform complex operations like finding a square of a number or square root of a number, we need to specify math library. To specify that library we use “-l” after “bc”.

Example:

#!/bin/bash

#square root
num=4
echo "scale=2;sqrt($num)" | bc -l

#power of a number
echo "scale=2;4^4" | bc -l

Output:

2.00
256

You can enter “man bc” in shell to get to know default math operations that a shell has to offer.

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *