bash 使用大于时应为整数表达式

bash integer expression expected when using greater than

我正在编写一个脚本,它的一部分输出一个数字 $stats,即 74.9,如果小于 100,则为失败,否则为通过。我试过了

do stuff
done

echo $stats

if [ $stats -gt 100 ]; then
echo "PASS"
else
echo "FAIL"
fi

但它失败了

72.4
./runme.sh: line 66: [: 72.4: integer expression expected
FAIL

72.4 显然不是一个整数。 Bash只支持整数运算。

常见的解决方法包括:

  • 截断。 if [ ${stats%.*} -gt 100 ]; then ...
  • 使用外部工具正确倒圆。 if [ $(echo "$stats > 100.0" | bc) = 1 ]; then...(可能会有更优雅的表达方式;但通常很痛苦。)
  • 正在转换为整数。如果您有固定的小数位数,则可行。 if [ ${stats%.*}${stats#*.} -gt 10000 ]; then...