Search code examples
bashaddition

Can't add float value in bash


I have a problem. This is my script:

#!/bin/bash
x_translate=0.96
for index in {2..6..2}
do
    gmx editconf -f mgdg_1.gro -o mgdg_$index.gro -translate  $x_translate 0 0
    x_translate=$(($x_translate+0.96))
    gmx editconf -f mgdg_1.gro -o mgdg_${index+1}.gro -translate  $x_translate 0 0
    x_translate=$(($x_translate+1.92))
done

I want to have in variable x_translate for example 1.92 then 3.84 then 4.8 etc. I get an error line 7: 0.96 + 0.96: syntax error: invalid arithmetic operator (incorrect tag is ".96 + 0.96")

For example, when I work with integers everything is ok, but with float values, I have a problem :( This works perfectly

x_translate=1
x_translate=$(($x_translate+1))

but I can't do this with float


Solution

  • bash doesn't support floating point arithmetic. You can try the bc utility:

    x_translate=$(bc <<< "$x_translate+0.96")