(变量除以数字)以浮点数打印-Bash [错误的数字]

时间:2018-11-03 00:01:33

标签: bash variables numbers integer

这是我的代码

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个小时的时间,可能是这个超级基本的可笑问题。但是我只是无法解决它,也不知道发生了什么。

1 个答案:

答案 0 :(得分:0)

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

/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环境变量设置不正确。