问题
In the following example, I find that the if [ $aaa==x ]
condition is always true.
for aaa in {x,y}
do
echo ---------
echo $aaa;
if [ $aaa==x ]
then echo this is x
elif [ $aaa==y ]
then echo this is y
fi
echo $aaa;
done;
That is, I always get the output as:
---------
x
this is x
x
---------
y
this is x
y
Even if I replace ==
with =
, the problem remains. Why?
回答1:
When you do:
if [ $aaa==x ]
You are expanding the parameter $aaa, then concatenating two =
and the letter x
, then testing whether this is a non-empty string (it always is).
if [ "$aaa" = x ]
Does what you want. Each part of the test should be passed as a separate argument, separated by whitespace.
Note that ==
isn't the standard syntax, you should use =
to test whether two strings are equal.
来源:https://stackoverflow.com/questions/45162210/why-is-my-if-condition-string-comparison-always-true