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
compare
to test for this.compare
is an ImageMagick command (for image processing/diffing).