How can I perform arithmetic operations in floating points using bash script [duplicate]

I need to add some real numbers in a script. I tried:

let var=2.5+2.5 

which gives me an error - invalid arithmetic operator and then I tried:

let var=2,5+2,5 

which does not give me an error, but it gives me a wrong result -2 in this case.

Why? How to add real numbers using let or other command?


Solution 1:

The first variant (let var=2.5+2.5) doesn't work because bash doesn't support floating point.

The second variant (let var=2,5+2,5) works, but it may not be what you wish because comma has another meaning in this case: it's a separator, command separator. So, your command is equivalent in this case with the following three commands:

let var=2
let 5+2
let 5

which are all valid and because of this you get var=2.

But, the good news is that you can use bc to accomplish what you wish. For example:

var=$(bc <<< "2.5+2.5")

Or awk:

var=$(awk "BEGIN {print 2.5+2.5; exit}")

Or perl:

var=$(perl -e "print 2.5+2.5")

Or python:

var=$(python -c "print 2.5+2.5")

Solution 2:

Bash doesn't handle floating point arithmetic.

If you really need fp arithmetic, use bc or dc. E.g.,

var=$(bc <<< "2.5+2.5")
echo "$var"

will output 5.0, or with dc (lots of fun, it's reverse polish notation):

var=$(dc <<< "2.5 2.5 + p")
echo "$var"

will also output 5.0.

Solution 3:

zsh is another shell different to bash that allows floating point in the shell. If you use zsh instead of bash, which do support let using floating points you don't need to modify the script. Just install it using sudo apt-get install zsh and then using it in your script with the shebang #!/usr/bin/zsh or using the shell. Demostration:

➜  ~  let var=2.5+2.5                      
➜  ~  echo $var
5.0000000000

The script should work fine since zsh implemented all the functions that bash has and more. Your second example will not work because the comma (,) is interpreted by the shells as separator. It tells to execute the command let with var=2 5+2 and 2.