在Bash中如何测试一个字符串是否比另一个字符串“更大"? [英] How does testing if a string is 'greater' than another work in Bash?
本文介绍了在Bash中如何测试一个字符串是否比另一个字符串“更大"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Bash中,我可以编写以下测试
In Bash I can write the following test
[[ "f" > "a" ]]
导致返回0,即true. bash实际上如何执行此字符串比较?根据我的理解,>
进行整数比较.是否尝试比较操作数的ASCII值?
which results in returning 0, i.e. true. How does bash actually perform this string comparison? From my understanding >
does an integer comparison. Does it try to compare the ASCII value of the operands?
推荐答案
来自help test
:
STRING1 > STRING2
True if STRING1 sorts after STRING2 lexicographically.
在内部,bash为此使用strcoll()
或strcmp()
:
Internally, bash either uses strcoll()
or strcmp()
for that:
else if ((op[0] == '>' || op[0] == '<') && op[1] == '\0')
{
if (shell_compatibility_level > 40 && flags & TEST_LOCALE)
return ((op[0] == '>') ? (strcoll (arg1, arg2) > 0) : (strcoll (arg1, arg2) < 0));
else
return ((op[0] == '>') ? (strcmp (arg1, arg2) > 0) : (strcmp (arg1, arg2) < 0));
}
后者实际上是比较ASCII码,前者(启用语言环境时使用)执行更具体的比较,该比较适合在给定的语言环境中进行排序.
The latter actually compares ASCII codes, the former (used when locale is enabled) performs a more specific comparison which is suitable for sorting in given locale.
这篇关于在Bash中如何测试一个字符串是否比另一个字符串“更大"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文