Why is my “if” condition (string comparison) always true?

百般思念 提交于 2020-06-03 07:57:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!