When I run this script in bash:
#!/bin/bash
str="no"
if [ "$str"="yes" ]; then
echo "condition 1 is true"
fi
if [ "$str"=="yes" ]; then
echo "condition 2 is true"
fi
if [[ "$str"="yes" ]]; then
echo "condition 3 is true"
fi
if [[ "$str"=="yes" ]]; then
echo "condition 4 is true"
fi
if (( "$str"="yes" )); then
echo "condition 5 is true"
fi
if (( "$str"=="yes" )); then
echo "condition 6 is true"
fi
To my surprise, I get:
condition 1 is true
condition 2 is true
condition 3 is true
condition 4 is true
condition 5 is true
condition 6 is true
Note that $str
is set to no
, not yes
.
I don't fully understand the difference between =
and ==
(at least, not in this bash context, I do in other languages) or between putting the if condition single [ ... ]
or double [[ ... ]]
or double (( ... ))
brackets.
However I'm obviously something very wrong here, but I can't see it?
First and foremost, not having a spaces around the operators, you're actually testing (for instance)
[ "no=yes" ]
which will evaluate as true (non-empty string).
[...]
is testing using [
external test command (presumably /bin/[
) and [[...]]
is shell (bash or ksh for instance) built-in test. For test =
and ==
have the same meaning. Which in case of built-in test ([[...]]
) is actually evaluated for a pattern match: i.e. [[ yeees == y*s ]]
is also true.
((...))
is arithmetic evaluation. =
is an assignment, and ==
tests equality. In my case (could come down to bash version) #5 actually yields false unless I've set yes=1
beforehand as the evaluation return value assigned... in this case new variable named no
since that is what str
pointed (resolved) to. For the comparison, this arithmetic comparison will return true, if values of both variables are equal... which literally means (( no == yes ))
or in test syntax [[ "$no" -eq "$yes" ]]
. If neither no
nor yes
are set, two 0s are compared.