Bash - 测试一个字符串是否比另一个字符串"更大" - 它是如何在内部工作的?

hel*_*hod 23 bash numeric-conversion

在Bash中,我可以编写以下测试

[[ "f" > "a" ]]
Run Code Online (Sandbox Code Playgroud)

这导致返回0,即为真.bash如何实际执行此字符串比较?从我的理解>做一个整数比较.它是否尝试比较操作数的ASCII值?

Mic*_*rny 14

来自help test:

  STRING1 > STRING2
                 True if STRING1 sorts after STRING2 lexicographically.
Run Code Online (Sandbox Code Playgroud)

在内部,bash使用strcoll()strcmp()为此:

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));
  }
Run Code Online (Sandbox Code Playgroud)

后者实际上比较ASCII码,前者(在启用语言环境时使用)执行更具体的比较,适合在给定的语言环境中进行排序.


Gor*_*son 8

这是按字母顺序排列的比较(AI​​UI排序顺序可能受当前区域设置的影响).它比较每个字符串的第一个字符,如果左边的那个字符串值较高则为真,如果低于它则为false; 如果它们是相同的,那么它会比较第二个字符等.

这是一样的整数比较,为您使用[[ 2 -gt 1 ]](( 2 > 1 )).为了说明字符串和整数比较之间的区别,请考虑以下所有内容都是"true":

[[ 2 > 10 ]]     # because "2" comes after "1" in ASCII sort order
[[ 10 -gt 2 ]]   # because 10 is a larger number than 2
(( 10 > 2 ))     # ditto
Run Code Online (Sandbox Code Playgroud)

这里有一些更多的测试,作为字符串比较,但对于整数比较将是假的:

[[ 05 < 5 ]]    # Because "0" comes before "5"
[[ +5 < 0 ]]    # Because "+" comes before the digits
[[ -0 < 0 ]]    # Because "-" comes before the digits
[[ -1 < -2 ]]   # Because "-" doesn't change how the second character is compared
Run Code Online (Sandbox Code Playgroud)