The Bash shell environment can perform basic arithmetic operations using commands such as let, (()), and []. The tools expr and bc are also useful for performing advanced operations.
The let command can be used to perform basic operations directly. When using let, just use the variable name without the $ prefix. E.g:
#!/bin/bash
no1 = 4;
no2=5;
let result=no1+no2
echo $result
Increment operation: let no1++
Decrement operation: let no1--
Shorthand: let no+=6
let no-=6
The [] operator can also be used like the let command: result=$[ no1 + no2], it is legal to use the $ prefix inside [], for example:
result=$[ $no1 + 5]
When using the (()) operator, use the format $variable name. Such as: result=$(( no1 + 50))
expr can also be used for basic operations:
result=`expr 3 + 4`
result=$(expr $no1 + 5)
None of the previous methods support floating point numbers and can only operate on integers.
bc, the exact calculator, is an advanced cohabitation for arithmetic operations. It has many options. We can perform floating point operations and use advanced functions such as:
echo "4 * 0.56" | bc
2.24
no=54;
result=`echo "$no * 1.5" | bc`
echo $result
81.0
Additional parameters can be passed to bc with prefixes to the operation with
semicolon as delimiters through stdin.
Decimal places scale with bc: In the following example the scale=2
parameter sets the number of decimal places to 2. Hence, the output
of bc will contain a number with two decimal places:
echo "scale=2;3/8" | bc
0.37
Base conversion with bc: We can convert from one base number system to
another one. Let us convert from decimal to binary, and binary to octal:
#!/bin/bash
Desc: Number conversion
no=100
echo "obase=2;$no" | bc
1100100
no=1100100
echo "obase=10;ibase=2;$no" | bc
100
Calculating squares and square roots can be done as follows:
echo "sqrt(100)" | bc #Square root
echo "10^10" | bc #Square