Assignment(=
) in bash scripts is also compare operator in bash.
See this example:
if [ "$a" = "$b" ]
Note the whitespace framing the =
. In this case we are comparing "$a"
and "$b"
.
if [ "$a"="$b" ] is not equivalent to the above.
Testing with example:
kasiay@kasiyaPC~:$ a=2
kasiay@kasiyaPC~:$ b=3
Then we run if [ "$a" = "$b" ]; then echo "equal"; else echo "not equal"; fi
, the result is "not equal" and it's true result.
But if we rub if [ "$a"="$b" ]; then echo "equal"; else echo "not equal"; fi
, the result is "equal" and it's wrong result!!
Why in this case we are wrong result?
When we are using if [ "$a"="$b" ]
, it parsing as if [ A_TOKEN ]
, then in this case the if condition always return true result. for example:
if [ "$a"="$b" ]; then echo "TRUE"; fi
#result is TRUE
if [ 2=3 ]; then echo "TRUE"; fi
#result is TRUE
if [ anything ]; then echo "TRUE"; fi
#result is TRUE
Both =
and ==
are string comparison.
The ==
comparison operator behaves differently within a
double-brackets
test than within single brackets.
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
links:Comparison Operators
Where you are using wrong statement?
In if ["$P1"=="$P2"];then
, should be if [ "$P1" == "$P2" ];then
. Spaces around ==
and also after and before brackets.