bash - (变量除以数字)以浮点数打印 - 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 个小时的时间。但我无法修复它,我不知道发生了什么。
解决方案
我从字面上复制了您的脚本,并尝试了以下所有方法,一切都按预期工作。
/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
环境变量设置不正确。
推荐阅读
- amazon-web-services - 我正在为我的 QnA 应用程序构建新闻提要,我不知道从哪里开始
- python - 内核问题 Anaconda 与 R
- vue.js - 如何使用方案中的其他文本颜色而不是主要颜色?
- loops - 如何在Stata中将两个循环变成一个双循环?
- c++ - 嵌套 std::map 的单行查找
- java - 如何解决 selenium/java 中的断言错误?
- github - 使用jenkins pipeline dsl构建jar并从github下载
- javascript - 设计有关处理程序的 React 组件架构的最佳方法是什么?
- java - 线程“pool-1-thread-1”中的异常 java.lang.NullPointerException:无法调用“java.util.Map.entrySet()”,因为“contextMap”为空
- azure - Azure 突触分析并行插入临时表