Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

numeric conversion - How does testing if a string is 'greater' than another work in Bash?

In Bash I can write the following test

[[ "f" > "a" ]]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From help test:

  STRING1 > STRING2
                 True if STRING1 sorts after STRING2 lexicographically.

Internally, bash either uses strcoll() or strcmp() for that:

else if ((op[0] == '>' || op[0] == '<') && op[1] == '')
  {
    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));
  }

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...