Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
user1161080 Avatar asked Jan 24 '12 00:01

user1161080


2 Answers

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.
like image 166
paxdiablo Avatar answered Sep 17 '22 14:09

paxdiablo


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
like image 29
SiegeX Avatar answered Sep 19 '22 14:09

SiegeX