首页 > 解决方案 > (变量除以数字)以浮点数打印 - Bash [错误数字]

问题描述

这是我的一段代码

if [ $totalavg -gt 1000000 ]; then
    printf "%0.1f MB/s (average)\n" $(echo "scale=1; $totalavg/100000" | bc)
elif [ $totalavg -gt 1000 ]; then
    printf "%0.1f KB/s (average)\n" $(echo "scale=1; $totalavg/1000" | bc)
else
    printf "%i B/s (average)\n" "$totalavg"
fi

totalavg 变量是从 /proc/ 文件中获取的整数。这一切都很好,直到整数大于 1000 才能到达 if 语句之一,结果证明

./script.sh: row (with second if above 1000): printf: 1.7: wrong number

我可能因为这个超级基本的可笑问题浪费了 2 个小时的时间。但我无法修复它,我不知道发生了什么。

标签: bashvariablesnumbersinteger

解决方案


我从字面上复制了您的脚本,并尝试了以下所有方法,一切都按预期工作。

/tmp> totalavg=500 ./script.sh
500 B/s (average)
/tmp> totalavg=5000 ./script.sh
5.0 KB/s (average)
/tmp> totalavg=50000 ./script.sh
50.0 KB/s (average)
/tmp> totalavg=5000000 ./script.sh
50.0 MB/s (average)
/tmp> totalavg=50000000 ./script.sh
500.0 MB/s (average)
/tmp> totalavg=1000 ./script.sh
1000 B/s (average)
/tmp> totalavg=1001 ./script.sh
1.0 KB/s (average)
/tmp> totalavg=999 ./script.sh
999 B/s (average)
/tmp> totalavg=999999 ./script.sh
999.9 KB/s (average)
/tmp> totalavg=1000000 ./script.sh
1000.0 KB/s (average)
/tmp> totalavg=1000001 ./script.sh
10.0 MB/s (average)

/tmp> cat script.sh
#!/bin/bash

if [ $totalavg -gt 1000000 ]; then
    printf "%0.1f MB/s (average)\n" $(echo "scale=1; $totalavg/100000" | bc)
elif [ $totalavg -gt 1000 ]; then
    printf "%0.1f KB/s (average)\n" $(echo "scale=1; $totalavg/1000" | bc)
else
    printf "%i B/s (average)\n" "$totalavg"
fi

您可以尝试将脚本复制到其他地方并在那里运行吗?或者您的$totalavg环境变量设置不正确。


推荐阅读