In the POSIX toolchest, expr
and awk
can be used to compare strings.
Both use strcoll()
for the comparison (same as sort
: the locale's collation order), but you can set the locale to C to get a strcmp()
type of comparison. For things like HH:MM:SS it doesn't matter anyway.
if expr "$time1" '<' "$time2" > /dev/null; then
printf '%s\n' "$time1 was before $time2"
fi
Now, again it doesn't matter for HH:MM:SS, but in the general case, note that expr
will do a numeric comparison if the operands are decimal integer numbers and do string comparison otherwise. That means that for instance 2
will be seen as less than 10
even though strcmp()
or strcoll()
would say otherwise.
Also, expr
will fail if the operands are expr
operators:
$ x=+ y=-; expr "$x" '<' "$y"
expr: syntax error
You can work around both problems by prefixing the operands with something that prevents them from being taken as numbers or operators:
expr "x $x" '<' "x $y"
With awk
, you have a similar problem. You'll need:
awk 'BEGIN{exit(!(""ARGV[1] < ""ARGV[2]))}' "$x" "$y"
To make sure the comparison is a string comparison and not a number comparison.
You can use helper functions like:
compare() {
expr "x $1" "$2" "x $3"
}
or:
compare() {
awk 'BEGIN{exit(!(""ARGV[1] '"$2"' ""ARGV[2]))}' "$1" "$3"
}
And use as:
if compare "$time1" '<' "$time2"; then
printf '%s\n' "$time1 was before $time2"
fi
In any case, as always, on Solaris, you need to make sure /usr/xpg4/bin
is before /bin
and /usr/bin
in $PATH
otherwise you get antiquated non-standard utilities. In particular, /bin/awk
on Solaris won't work with the above code. It's the one from the 70s without ARGV
.
For that same reason, you don't want to use #!/bin/sh
in your she-bang. The standard/POSIX sh
on Solaris is /usr/xpg4/bin/sh
(though in Solaris 11, /bin/sh
changed from the Bourne shell to ksh93 which makes it a lot more POSIX compliant; also note that /usr/xpg4/bin/sh
has many conformance bugs).
if [ "$a" \< "$b" ]; then ...
will not work even with/bin/ksh
,/usr/xpg4/bin/sh
or theksh93
from solaris 11.ksh93
does support the<
and>
operators, but only with[[
, not with[
ortest
. – Feb 09 '19 at 05:15