Add, Subtract, Multiply, Division with Numbers in Bash

This article will introduce how to Add, Subtract, Multiply, Division with integer numbers in Bash.

1. Add

You can add 2 variables using parentheses twice like this.

#!/bin/bash

a=10
b=20

sum=$(($a + $b))
echo $sum

Output:

30

1.1 Add with expr

expr is a command used to perform arithmetic operations. You can also use it for addition.

sum=$(expr $a + $b)

You can also use quotes instead of parentheses to use expr.

sum=`expr $a + $b`

2. Subtract

You can do subtraction as follows.

#!/bin/bash

a=10
b=20

sum=$(($a - $b))
echo $sum

Output:

-10

2.1 Subtract with expr

You can use expr to do subtraction.

sum=$(expr $a - $b)

You can also use quotes instead of parentheses to use expr.

sum=`expr $a - $b`

3. Multiply

You can do direct multiplication using two parentheses as follows.

#!/bin/bash

a=10
b=20

sum=$(($a * $b))
echo $sum

Output:

200

3.1 Multiply with expr

When using expr for multiplication, you must use \* instead of just *.

sum=$(expr $a \* $b)

You can also use quotes instead of parentheses to use expr.

sum=`expr $a \* $b`

4. Division

You can use two parentheses to do a division operation.

#!/bin/bash

a=10
b=20

sum=$(($a / $b))
echo $sum

Output:

0

4.1 Division with expr

You can use expr to do division as follows.

sum=$(expr $a / $b)

You can also use quotes instead of parentheses to use expr.

sum=`expr $a / $b`
codechachaCopyright ©2019 codechacha