在shell脚本中,我们如何只用一个if条件比较(整数和浮点数)、(浮点数和浮点数)、(浮点数和整数)、(整数和整数)。

我有几个例子

 set X=3.1
  set Y=4.1
  if [ $X < $Y ] then
    echo "wassup"
  endif

但是从 cron 作业运行上述内容似乎不起作用。

最佳答案

在 bash 中执行浮点运算的方法是使用 bc,它几乎在所有 linux 发行版上都可用。

# bc will return 0 for false and 1 for true
if [ $(echo "23.3 > 7.3" | bc) -ne 0 ]
then
  echo "wassup"
fi

linux journal 上有一个关于 bash 中使用 bc 的浮点数学的 good article

关于linux - shell脚本中整数和浮点数的比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9939546/

10-11 22:09
查看更多