且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Bash中如何测试一个字符串是否比另一个字符串“更大"?

更新时间:2023-11-28 23:43:16

来自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.