Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "[[ 10 < 2 ]]" true when comparing numbers in bash? [duplicate]

Tags:

bash

shell

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.

like image 545
rajen Avatar asked Mar 12 '17 08:03

rajen


People also ask

What is the difference between and [[ in bash?

(difference) [[ is a keyword. ​ [[ is a shell keyword (invoke type [[ in Bash to confirm this). Like the [ builtin, the [[ keyword belongs to Bash; but it does not behave like a command. (similarity) [[ requires a space after.

How do I compare two numbers in bash?

Example: Comparing numbers in bash Find out if 5 greater than 10, enter (type command at terminal): x=5 y=10 [ $x -gt $y ] echo $? In a bash shell non-zero output means false result i.e. $x is not greater than $y. Try the following example (type command at terminal):

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does $() mean bash?

The expression $(command) is a modern synonym for `command` which stands for command substitution; it means run command and put its output here. So. echo "Today is $(date).


1 Answers

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

like image 136
Denis Itskovich Avatar answered Oct 14 '22 01:10

Denis Itskovich