为什么我的“如果"条件(字符串比较)始终为true?

问题描述:

在下面的示例中,我发现if [ $aaa==x ]条件始终为真.

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?

操作时:

if [ $aaa==x ]

您正在扩展参数$ 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.