gpt4 book ai didi

bash - 如何在 bash 中编写小数 for 循环

转载 作者:行者123 更新时间:2023-11-29 09:38:09 28 4
gpt4 key购买 nike

我怎样才能在 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

最佳答案

两种方法:

使用bc

shell 不支持 float ,但标准实用程序 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

关于bash - 如何在 bash 中编写小数 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27073698/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com