Reputation: 5619
It is seems to be an easy question, I wonder why googling didn't give anything helpful -- nor in StackOverflow, nor in tutorials. I just need to check using bash that a condition is false.
Of what I found I tried
if ! [ 0==2 ]; then echo Hello; fi
and
if [ ! 0==2 ]; then echo Hello; fi
none of them print Hello.
I found only two similar questions, but the end answer in both cases was restructured code to not use the "false" condition.
Upvotes: 41
Views: 72658
Reputation: 2818
If you are using the test
command ([..]
) you can use the comparison option for integer: -eq
, equal, and -ne
, not equal.
if [ 0 -eq 2 ]; then echo true ; else echo false ; fi # false
if [ 0 -eq 0 ]; then echo true ; else echo false ; fi # true
if [ 0 -ne 2 ]; then echo true ; else echo false ; fi # true
if [ 0 -ne 0 ]; then echo true ; else echo false ; fi # false
In bash the operator [...]
is the equivalent of test
, a command that checks file types and compare values; test is an internal command: if you ask to your shell with type [
it will answer [ is a built in shell command
. You can find the binary too usually in /usr/bin/[
.
The SYNOPSIS is test EXPRESSION
, as you can read from man test
or from info coreutils test invocation
.
An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status.
This is an excerpt from man that cam help to understand a little better
( EXPRESSION ) EXPRESSION is true. So it's easy to incur in the error to consider as an operation 0==1
. (The operation is 0 == 1
with spaces, 0==1
is an expression).
! EXPRESSION EXPRESSION is false.
From info coreutils test invocation
you can read about the exit status of test.
Exit status:
0 if the expression is true,
1 if the expression is false,
2 if an error occurred.
Upvotes: 4
Reputation: 136208
In addition to bash's mathematical evaluations, you can use boolean expressions instead of if
:
[max@localhost:~] $ (( 0 == 0 )) && echo True || echo False
True
[max@localhost:~] $ (( 0 != 0 )) && echo True || echo False
False
Upvotes: 4
Reputation: 4325
Do you mean:
if ! [ 0 == 2 ]; then
echo Hello;
fi
You lacked space around the equality operator.
This might be the time to read http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html - especially the sections about if then else and operators. I usually have this open when I am writing scripts..
Upvotes: 69
Reputation: 15165
For mathematical evaluations use (( ))
in bash. For text use [[ ]]
.
if (( $i == 0 )); then
echo "i is 0"
else
echo "i is unequal 0"
Read more here about comparison operators in bash.
And more on double parenthesis
Upvotes: 10