8

When I run

if [[ 10 < 2 ]];
  then echo "yes";
else echo "no"; 
fi

in shell, it returns yes. Why? should it be no? And When I run

if [[ 20 < 2 ]];
  then echo "yes";
else echo "no";
fi

it returns no.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
rajen
  • 89
  • 1
  • 1
  • 5
  • When you were asking the question, the interface should have showed a series of search results for similar questions. Were none of those flagged in the header shown there? – Charles Duffy Mar 23 '17 at 16:33

1 Answers1

18

Because you compare strings according to Lexicographical order and not numbers

You may use [[ 10 -lt 2 ]] and [[ 20 -lt 2 ]]. -lt stands for Less than (<). For Greater than (>) -gt notation can be used instead.

In bash double parenthesis can be used as well for performing numeric comparison:

if ((10 < 2)); then echo "yes"; else echo "no"; fi

The above example will echo no

Denis Itskovich
  • 4,383
  • 3
  • 32
  • 53
  • I use bash shell – rajen Mar 12 '17 at 09:02
  • 2
    Sometimes I feel that JavaScript should not be the scapegoat of programming notwithstanding its obfuscated syntax and drunk typecasting wizardry because this ‘feature’ of Bash feels like outright treachery that deserves punishment in the ninth circle of hell. (I was owned by bash string comparison today...) – Andreï V. Kostyrka May 24 '22 at 22:50