Search code examples
bashshellalphabetical

Shell scripting - which word is first alphabetically?


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?


Solution

  • 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:

    1. it looks nicer; and
    2. the [[ variant is much more expressive and powerful.