外壳中的浮点比较 [英] Floating point comparison in shell

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

问题描述

您能给我建议在Bash脚本中进行浮点比较的语法吗?理想情况下,我想将其用作if语句的一部分.这是一个小代码段:

Can you please suggest to me the syntax for doing floating point comparison in a Bash script? I would ideally like to use it as part of an if statement. Here is a small code snippet :

key1="12.3"
result="12.2"

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

推荐答案

bash不执行浮点操作,请使用awk

bash doesn't do floats, use 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,您可能也想尝试使用它们

there are other shells that can do floats, like zsh or ksh, you might like to try using them as well

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

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