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
.
(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.
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):
$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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With