Shell脚本中的浮点比较

时间:2010-03-11 12:18:13

标签: linux bash unix shell

你能否告诉我在Bash脚本中进行浮点比较的语法?理想情况下,我希望将它用作if语句的一部分。这是一个小代码片段:

key1="12.3"
result="12.2"

if (( $result <= $key1 ))
then
    # some code here
fi

6 个答案:

答案 0 :(得分:57)

bc是你的朋友:

key1="12.3"
result="12.2"
if [ $(bc <<< "$result <= $key1") -eq 1 ]
    then
    # some code here
fi

请注意有些模糊的 here string <<<)表示法,作为echo "$result <= $key1" | bc的一个不错的替代方法。

此外,类似un-bash的bc true 打印1,为 false 打印0

答案 1 :(得分:18)

bash不做浮动,使用awk

key1=12.3
result=12.5
var=$(awk 'BEGIN{ print "'$key1'"<"'$result'" }')    
# or var=$(awk -v key=$key1 -v result=$result 'BEGIN{print result<key?1:0}')
# or var=$(awk 'BEGIN{print "'$result'"<"'$key1'"?1:0}')
# or 
if [ "$var" -eq 1 ];then
  echo "do something"
else
  echo "result more than key"
fi

还有其他可以执行浮动的shell,比如zsh或ksh,你可能也想尝试使用它们

答案 2 :(得分:6)

与bc另一个简单明了的方法是:

if ((`bc <<< "10.21>12.22"`)); then echo "true"; else echo "false"; fi

答案 3 :(得分:4)

使用exit()的{​​{1}}功能使其几乎可读。

awk

请注意,由于key1=12.3 result=12.5 # the ! awk is because the logic in boolean tests # is the opposite of the one in shell exit code tests if ! awk "{ exit ($result <= $key1) }" < /dev/null then # some code here fi 已使用退出值,因此无需重复使用[运算符。

答案 4 :(得分:1)

### The funny thing about bash is this:
> AA=10.3
> BB=10.4
### It needs `$` for compare
> [[ $AA > $BB ]] && echo Hello
> [[ $AA < $BB ]] && echo Hello
Hello

是的,我知道这是作弊但它有效。科学记数法在这里不起作用。

答案 5 :(得分:0)

直到现在我一直在使用bc,在某些发行版中发现没有安装bc,并且我不想通过sudo apt install bc,但是python在那儿。使用python:

  if python -c "import sys; sys.exit(0 if float($float_1) > float($float_2) else 1)"; 
    then
    echo "true"
         else
           echo "false"
  fi