Shell脚本中整数和浮点数的比较 [英] comparison of integer and floating point numbers in shell script

查看:372
本文介绍了Shell脚本中整数和浮点数的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在shell脚本中,我们如何仅将if条件与(整数和浮点),(浮点和浮点),(浮点和整数),(整数和整数)进行比较.

In shell script how can we compare (integer and floating point) ,(flaoting point and floating point),(floating point and integer),(integer and integer) with only one if condition.

我有一些类似

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

但是从cron作业运行上述命令似乎不起作用.

But running the above from cron job doesnt seem to work.

推荐答案

在bash中执行浮点运算的方法是使用bc ,几乎在所有Linux发行版中都可以使用.

The way to carry out floating point operations in bash is to use bc which is available on almost all linux distributions.

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

在Linux期刊上有一篇关于使用bc在bash中进行浮点数学运算的好文章.

There's a good article available on linux journal about floating point math in bash using bc.

这篇关于Shell脚本中整数和浮点数的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆