Shell:为什么if-condition总是如此

时间:2017-07-18 09:06:33

标签: shell if-statement

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

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;

也就是说,我总是得到输出:

---------
x
this is x
x
---------
y
this is x
y

即使我将==替换为=,问题仍然存在。为什么? 谢谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

当你这样做时:

if [ $aaa==x ]

您正在扩展参数$ aaa,然后连接两个=和字母x,然后测试这是否为非空字符串(它始终是)。

if [ "$aaa" = x ]

你想做什么。测试的每个部分都应作为单独的参数传递,用空格分隔。

请注意,==不是标准语法,您应该使用=来测试两个字符串是否相等。