47

In Bash, is there a simple way to test if one string is lexicographically less than or equal to another?

I know you can do:

if [[ "a" < "b" ]]

for testing strict inequality, or

if [[ 1 -le 1 ]]

for numbers. But -le doesn't seem to work with strings, and using <= gives a syntax error.

3
  • Use compare to test for this. Commented Jan 22, 2014 at 21:59
  • 3
    @WilliamMorrison On my Debian compare is an ImageMagick command (for image processing/diffing).
    – bryn
    Commented Jan 23, 2014 at 0:46
  • 2
    @bryn gotta "love" those ultra generic ImageMagick command names :-) Commented Oct 2, 2015 at 9:40

6 Answers 6

62

Just negate the greater than test:

if [[ ! "a" > "b" ]]
19

You need to use || with an additional condition instead of <=:

[[ "$a" < "$b" || "$a" == "$b" ]] 
6
  • 2
    Use [ ! "$a" -gt "$b" ] in POSIX
    – anubhava
    Commented Oct 2, 2015 at 9:44
  • 12
    Isn't -gt for integers only? Commented Oct 2, 2015 at 9:45
  • 2
    @CiroSantilli烏坎事件2016六四事件法轮功 works for me: test "5" -gt "6" ; echo $? —> 1, and test "7" -gt "6" ; echo $? —> 0
    – KajMagnus
    Commented Apr 8, 2017 at 19:49
  • 3
    @KajMagnus You're testing with integers, not arbitrary strings. test "abc" -gt "xyz" ; echo $? --> "-bash: test: abc: integer expression expected". Also, string comparison order is different: as integers, "10" is greater than "9", but as strings it's the other way around because "1" comes before "9" in lexical sorting order. Commented Jun 22, 2017 at 14:42
  • 1
    @ciro-santilli I added a new answer with POSIX syntax
    – t0r0X
    Commented Oct 8, 2018 at 17:50
4

expr POSIX method

I believe [ a < b ] is a Bash extension. The best POSIX method I could find was this as documented at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html:

expr abc \< acb >/dev/null || echo fail
! expr abc \< aac >/dev/null || echo fail

or with slightly worse golfing and a subshell:

[ "$(expr abc \< acb)" = 1 ] || echo fail
[ "$(expr abc \< aac)" = 0 ] || echo fail

But because expr \< is completely insane and:

  • automatically determines is something is an integer or not to choose numerical vs lexicographical comparison, e.g. expr 2 \< 10 is 1
  • has undefined behaviour for magic keywords length, substr, index and match

you generally want to add a trash x to force your variable to be a non-reserved string as in:

x1=aac
x2=abc
x3=acb
expr x"$x2" \< x"$x3" >/dev/null || echo fail
! expr x"$x2" \< x"$x1" >/dev/null || echo fail

and so for less than or equal I'd just:

expr x"$x1" \< x"$x2" >/dev/null || [ "$x1" = "$x2" ] || echo fail

sort POSIX workaround

Just for fun, use expr instead.

Not infinitely robust to strings with newlines, but when is it ever when dealing with shell scripts?

string_lte() (
  s="$(printf "${1}\n${2}")"
  [ "$(printf '%s' "$s" | sort)" = "$s" ]
)
string_lte abc adc || echo fail
string_lte adc adc || echo fail
string_lte afc adc && echo fail
2
  • sort -c is in POSIX, so we can have string_lte() { printf '%s\n' "$1" "$2" | sort -c }. Sadly sort -z isn't portable, but if you have it, we can use \0 in place of \n to get a newline-safe comparison. (N.B. your printf is broken if either argument contains %!) Commented Feb 6 at 11:07
  • 1
    BTW, if command; then exit 0; else exit 1; fi can generally be replaced by command; exit (or command || false; exit if we really care about replacing all failure statuses by 1) - and the exit isn't necessary at end of subshell. Commented Feb 6 at 11:13
3

You can flip the comparison and sign around and test negatively:

$ a="abc"
$ b="abc"
$ if ! [[ "$b" > "$a" ]] ; then  echo "a <= b" ; fi
a <= b

If you want collating sequence of "A" then "a" then "B"... use:

shopt -s nocaseglob
0
2

If you can use the Bash syntax, see the answers from @anubhava and @gordon-davisson. With POSIX syntax you have two options (note the necessary backslashes!):

using the -o operator (OR):

[ "$a" \< "$b" -o "$a" = "$b" ] && echo "'$a' LTE '$b'" || echo "'$a' GT '$b'"

or using negation:

[ ! "$a" \> "$b" ] && echo "'$a' LTE '$b'" || echo "'$a' GT '$b'"

I prefer the first variant, because imho it's more readable.

3
  • 1
    I think it is an extension still. Or can you find a clear POSIX quote? pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html seems to even mention it on the rationale: "Some additional primaries newly invented or from the KornShell appeared in an early proposal as part of the conditional command ([[]]): s1 > s2, s1 < s2, str = pattern, str != pattern, f1 -nt f2, f1 -ot f2, and f1 -ef f2. They were not carried forward into the test utility [...]". Commented Oct 8, 2018 at 17:58
  • See here: pubs.opengroup.org/onlinepubs/9699919799/utilities/… But yes, it's marked [OB XSI]: OB = Obsolescent [Option End] The functionality described may be removed in a future version of this volume of POSIX.1-2017. Strictly Conforming POSIX Applications and Strictly Conforming XSI Applications shall not use obsolescent features.
    – t0r0X
    Commented Oct 9, 2018 at 19:04
  • XSI= The functionality described is part of the X/Open Systems Interfaces option. Functionality marked XSI is an extension to the ISO C standard. Application developers may confidently make use of such extensions on all systems supporting the X/Open System Interfaces option. I will stick with Bash syntax in the future.
    – t0r0X
    Commented Oct 9, 2018 at 19:11
-1

I use python: 's1="abc"; s2="cde"; if /usr/bin/python -c "exit('$s1'<'$s2')" ; then echo "s1>=s2" ; else echo "s1<s2" ; fi `

2
  • 1
    That gets broken when either argument contains '. Commented Feb 6 at 11:15
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 12 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.