bash为什么不按字典顺序而不是按数字来评估数字比较? [英] Why does bash evaluate comparison of numbers lexicographically not numerically?

查看:68
本文介绍了bash为什么不按字典顺序而不是按数字来评估数字比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释bash的" if "块的以下行为吗?

Could someone explain the following behavior of the "if" block of bash ?

我使用以下简单代码检查 first_value 是否小于 second_value

I use the following simple code check if the first_value is less than the second_value

first_value=67
second_value=2

if [[  "${first_value}" < "${second_value}" ]];
then 
    echo "Yes"
else 
    echo "No"
fi

问题是

如果 second_value 是1,2,3,4,5,6,10,11,...该块将返回否"

If the second_value is 1,2,3,4,5,6,10,11,... the block will return "No"

但是,如果 second_value 是7,8,9,则该块将返回是"(必须为否")

But if the second_value is 7,8,9 the block will return "Yes" (must be "No")

解决方法是使用" -lt "而不是"< ",但是我想了解" if "堵塞.

The fix is to use "-lt" instead of "<" but I want to understand such behavior of the "if" block.

bash版本是"GNU bash,版本4.2.46(2)-发行版(x86_64-redhat-linux-gnu)"

The bash version is "GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)"

操作系统为"CentOS Linux版本7.5.1804(核心)"

The OS is "CentOS Linux release 7.5.1804 (Core)"

推荐答案

关于您的问题:首先,if块不返回任何内容.它只执行一组语句或另一组语句,在您的情况下,它们会向stdout写一些东西.

As for your question: First, an if block does not return anything. It just executes one set of statements or another ones, which in your case write something to stdout.

现在对您所观察到的行为进行解释.

Now to the explanation of the behaviour you have observed.

< [[... ...]] 表达式中的运算符进行字典比较.例如在

The < operator in a [[ ... ]] expression does lexicographic comparison. For instance in

[[ 67 < 7 ]]

"67"在词汇上比"7"小,因此[[....]]返回状态代码0,这意味着if正在执行then部分,从而导致打印Yes.

"67" is lexically smaller than "7", and hence [[ .... ]] returns status code 0, which means that the if is executing the then part, which causes Yes to be printed.

这篇关于bash为什么不按字典顺序而不是按数字来评估数字比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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