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`
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash