linux - 如何在 shell 脚本中比较两个浮点值

标签 linux comparison shell conditional-statements bc

我必须在 shell 脚本中进行除法,最好的方法是:

result1=`echo "scale=3; ($var1 / $total) * 100"| bc -l`
result2=`echo "scale=3; ($var2 / $total) * 100"| bc -l`

但我想比较 $result1$result2

的值

使用 if test $result1 -lt $result2if [ $result1 -gt $result2 ] 无效:(

知道怎么做吗?

最佳答案

您可以使用 expr(1) 比较 float :

: nr@yorkie 3724 ; expr 3.1 '<' 3.3
1
: nr@yorkie 3725 ; expr 3.1 '<' 3.09
0

你也可以有 bc进行比较和计算:

if [ "$(echo $result1 '<' $result2 | bc -l)" -eq 1 ];then ... fi

终于ksh93可以做算术求值$(($result1 < $result2))使用 float ,尽管 bash 不能。

关于linux - 如何在 shell 脚本中比较两个浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2769671/

相关文章:

linux - Linux内核进程调度器的FCFS算法

linux - 如何将文件复制到用户的主目录

java - 如何检查 XML 文档中是否存在子树

python - Python 与其他脚本语言相比如何?

linux - 无法获得这个简单的 sed 命令

bash - "plus colon"("+:") 在 shell 脚本表达式中是什么意思?

c++ - 将 Sublime Text 与 cmake(构建系统)结合使用

java - 为什么 ScheduledExecutorService.shutdown() 使用 100% 的 CPU?

python - 基于Multiindex和dataframe创建MultiIndex Dataframe(比较矩阵)

bash - 如何在 shell 中的指定行号中添加或删除字符?