Illegal Number when Comparing floats

时间:2015-07-31 19:48:32

标签: sh

if [ 3 -lt 6 ]; then
  echo "It works with ints"
fi

if [ 3.0 -lt 6.0 ]; then
  echo "It works with floats"
else
  echo "It doesn't work with floats"
fi

Comparing the integers in an "if" works just fine.

But it doesn't work when I do the same thing with floating point numbers, and gives me this output:

+ [ 3.0 -lt 6.0 ]
/tmp/hudson7259224562322746826.sh: 11: [: Illegal number: 3.0
+ echo It doesn't work with floats
It doesn't work with floats

1 个答案:

答案 0 :(得分:0)

根据bash联机帮助页(我最后的重点):

  

arg1 OP arg2OP-eq-ne-lt-le-gt或{{}之一1}}。如果-ge分别等于,不等于,小于,小于或等于,大于或大于或等于arg1,则这些算术二元运算符返回true。 arg2Arg1 可能是正整数或负整数。

换句话说,arg2在比较浮点值时没有原生支持。

如果您真的想要处理浮点数,那么最好选择 支持它的工具,例如bash

bc