rajen rajen - 8 months ago 22
Bash Question

Why [[ 10 < 2 ]] is true, while [[ 20 < 2 ]] is false?

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
.

Answer Source

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