如何在bash中写一个小数for循环

时间:2014-11-22 03:22:26

标签: bash

如何在bash

中写一个小数for循环

我收到类似

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

我正在尝试像

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

3 个答案:

答案 0 :(得分:4)

两种方法:

使用bc

shell不执行浮动,但标准实用程序bc执行浮动操作。这将循环:

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

示例输出:

$ 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

纯粹的bash解决方案,通过切换到百分之一

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

输出:

$ 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

答案 1 :(得分:2)

简而言之,你就是“不能”,因为Bourne shell不会“做”浮点数学。

但是,您可以使用其他可编写脚本的工具(如Perl)为您执行此操作:

 $ver = $(perl -e "print $ver + .01")

另请参阅bcawk或其他工具。

答案 2 :(得分:1)

Bash不支持浮点数,但有一个程序BC(最佳计算器)支持十进制算术。

upgradever="1.00"
newver="1.06"

for (( i=$(bc<<<"($upgradever*100)/1"); $i<$(bc<<<"$newver/0.01"); i++ )); do
      echo $(bc<<<"0.01 * $i")
done