为什么我的“如果"条件(字符串比较)始终为true? [英] Why is my "if" condition (string comparison) always true?

查看:148
本文介绍了为什么我的“如果"条件(字符串比较)始终为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.

这篇关于为什么我的“如果"条件(字符串比较)始终为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆