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.You'll want to use the [[ ]]
construct and print out the one that is less than the other
#!/bin/bash
var1="apple"
var2="bye"
if [[ $var1 < $var2 ]]; then
echo $var1
else
echo $var2
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With