How can you check which words is first alphabetically between two words? For example in the code
#!/bin/bash
var1="apple"
var2="bye"
if [ $var1 \> $var2 ]
then
echo $var1
else
echo $var2
fi
I want it to print apple, since apple comes before bye alphabetically, but it isnt working as intended. What am I doing wrong?
What you need to do to solve the immediate problem is reverse the sense of your statement, since the "less than" operator is <
rather than >
.
Doing so will get it working correctly:
if [ $var1 \< $var2 ]
Alternatively, you can use the [[
variant which doesn't require the escaping:
if [[ $var1 < $var2 ]]
I prefer the latter because:
[[
variant is much more expressive and powerful.