【问题标题】:(Variable divided by Number) printed in float - Bash [wrong number](变量除以数字)以浮点数打印 - Bash [错误数字]
【发布时间】:2019-04-07 04:55:34
【问题描述】:

这是我的一段代码

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

【问题讨论】:

    标签: bash variables numbers integer


    【解决方案1】:

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

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

    【讨论】:

    • 它不必是环境变量。
    • 噢...我的总平均数是这样计算的: received1=$(awk 'FNR == 4 {print $2}' /proc/net/dev) sleep 1s received2=$(awk ' FNR == 4 {print $2}' /proc/net/dev) let "totalavg=((received2+received1))" 仍然不知道如何在我这边解决它:(
    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多