I’m a bit baffled. I’m trying to compare string variables in a shell script to figure out if one value is lexically less (that is, would appear earlier in the dictionary) than another, but it doesn’t seem to work at all? Help!
I’m pretty sure you’re asking about the conditional string expressions in the test command, typically denoted in shell scripts with the [ and ] symbols (the first of which, as a complete piece of trivia, is actually a hard link to the test binary. Do the following to see it: ls /usr/bin/? or /bin/? instead!)
Anyway, you’re trying to do something like this:
if [ $stringvar1 > $stringvar2 ] ; then
echo $stringvar1 is greater than $stringvar2
echo $stringvar1 is not greater than $stringvar2
The problem with this notation, one that surprisingly few shell script books and articles mention, is that you need to escape the angle brackets or the shell will interpret them as redirection symbols!
Indeed, if you have stringvar1=test and stringvar2=me then running that test would actually create an output file called “me”, not at all what you want to accomplish!
Instead, here’s a snippet of code to experiment with that demonstrates the correct use of these string conditionals:
a="aardvark" # then try 'zebra'
if [ $a \< $b ] ; then
echo "$a is less than $b"
echo "$a is NOT less than $b"
Hope that helps clear up the mystery!