The Bash shell performs basic arithmetic operations using the let, (( )), and [] commands. The expr and bc utilities are used to perform advanced operations.
Math with the shell
How to do it...
- A numeric value is assigned to a variable the same way strings are assigned. The value will be treated as a number by the methods that access it:
#!/bin/bash no1=4; no2=5;
- The let command is used to perform basic operations directly. Within a let command, we use variable names without the $ prefix. Consider this example:
let result=no1+no2 echo $result
         Other uses of let command are as follows:
- Use this for increment:Â
$ let no1++
- For decrement, use this:
$ let no1--
- Use these for shorthands:
let no+=6 let no-=6
        These are equal to let no=no+6 and let no=no-6, respectively.
- Alternate methods are as follows:
       The [] operator is used in the same way as the let command:
result=$[ no1 + no2 ]
       Using the $ prefix inside the [] operator is legal; consider this example:
result=$[ $no1 + 5 ]
   The (( )) operator can also be used. The prefix variable names             with a $ within the (( )) operator:
result=$(( no1 + 50 ))
       The expr expression can be used for basic operations:
result=`expr 3 + 4` result=$(expr $no1 + 5)
   The preceding methods do not support floating point numbers,
   and operate on integers only.
- The bc application, the precision calculator, is an advanced utility for mathematical operations. It has a wide range of options. We can perform floating point arithmetic and use advanced functions:
echo "4 * 0.56" | bc 2.24 no=54; result=`echo "$no * 1.5" | bc` echo $result 81.0
The bc application accepts prefixes to control the operation. These are separated from each other with a semicolon.
- 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;22/7" | bc 3.14
- Base conversion with bc: We can convert from one base number system to another one. This code converts numbers from decimal to binary and binary to decimal:
#!/bin/bash Desc: Number conversion no=100 echo "obase=2;$no" | bc 1100100 no=1100100 echo "obase=10;ibase=2;$no" | bc 100
- The following examples demonstrate calculating squares and square roots:
echo "sqrt(100)" | bc #Square root echo "10^10" | bc #Square