You need to log in to create posts and topics.

How to Perform Arithmetic Operation for Floating Point in Bash?

I'm trying to run some arithmetic operation in Bash. The input values contain some floating values and so the bash failed to execute the code and display error message.

Bash Example to perform arithmetic operation:

a1=4.5
a2=3.9
a3=5.3
a4=6.1
a=3
let output=a1+a2+a3+a4/4
echo $output

The output of the above script is,

Sample Bash Output

Any way to fix the above error?

Solution:

The above formulae will not work for floating inputs on shell scripts. You need to use the BC in code.

BC is the simple command-line calculator.

The re-written program is,

a1=4.5
a2=3.9
a3=5.3
a4=6.1
a=4
output=`echo $a1+$a2+$a3+$a4/4 | bc`
echo $output

The output of the above script will print the value 14.7

Corrected Output

What's is changed?

  • You need to express the formulae inside the "`" symbol, find more information here
  • Using echo will print the output
  • BC is the simple terminal calculator which will handle float number.

That's it. This is how you can perform the Arithmetic operations with float number on Bash Shell Scripts.