How to write a decimal for loop in bash

advertisements

How can I write a decimal for loop in bash

I get an error like

((: upgradver=1.00: syntax error: invalid arithmetic operator (error token is ".00")

I am trying something like

upgradever=1.00
newver=1.06
for (($ver=$upgradever; $ver<$newver; $ver+=0.01))
do
    echo "Upgrade to $ver"
done


Two approaches:

Using bc

The shell does not do floats but the standard utility bc does. This will do your loop:

upgradever=1.00
newver=1.06

ver=$upgradever
while [ 1 = "$(echo "$ver < $newver" | bc -l)" ]
do
    echo "Upgrade to $ver"
    ver=$(echo "$ver + 0.01" | bc -l)
done

Sample output:

$ bash script.sh
Upgrade to 1.00
Upgrade to 1.01
Upgrade to 1.02
Upgrade to 1.03
Upgrade to 1.04
Upgrade to 1.05

Pure bash solution via switching to hundredths

upgradever=100
newver=106
for ((ver=$upgradever; $ver<$newver; ver+=1))
do
    printf -v version '%s.%02i' "$((ver/100))" "$((ver%100))"
    echo "Upgrade to $version"
done

Output:

$ bash  sscript.sh
Upgrade to 1.00
Upgrade to 1.01
Upgrade to 1.02
Upgrade to 1.03
Upgrade to 1.04
Upgrade to 1.05