Bash bc command

  • The full form of bc is Bash Calculator.
  • It is used for performing floating-point mathematical operations. Before you perform any arithmetic operation using bc command, make sure you set the value of a built-in variable called scale. This variable is used to set the number of decimal places. The default value of the scale variable is 0.

How to use bc command in Bash Shell?

variable=`echo "options; expression" | bc`

Here, we use backtick to run bc command and assign the output to a variable. In options part, we set variables like scale. Mathematical operations are performed in the expression part.

Example: Bash bc command

num1=75.5
num2=20
add=`echo "scale=4; $num1+$num2" | bc`
sub=`echo "scale=4; $num1-$num2" | bc`
multi=`echo "scale=4; $num1*$num2" | bc`
div=`echo "scale=4; $num1/$num2" | bc`
echo "Addition of $num1 and $num2 is $add"
echo "Subtraction of $num1 and $num2 is $sub"
echo "Multiplication of $num1 and $num2 is $multi"
echo "Division of $num1 and $num2 is $div"

Output of the above program

Addition of 75.5 and 20 is 95.5
Subtraction of 75.5 and 20 is 55.5
Multiplication of 75.5 and 20 is 1510.0
Division of 75.5 and 20 is 3.7750

Check out these related Bash Shell Tutorial