3

这按预期工作: -

x="None of the specified ports are installed"
if [ "$x" = "None of the specified ports are installed" ]; 
    then echo 1; 
    else echo 0; 
fi

我得到1了,这是我所期待的。

但这不起作用:-

y="`port installed abc`"
if [ "$y" = "None of the specified ports are installed" ]; 
    then echo 1; 
    else echo 0; 
fi

我得到0了,这不是我所期望的;虽然

echo $y 

None of the specified ports are installed.

这里的主要区别是$yport installed abc命令动态确定。但是为什么这会影响我的比较呢?

4

2 回答 2

2

仔细注意。

未安装指定端口

不相等

未安装任何指定的端口。
                                         ^
                                        /
                          在那里  - 

另外的选择

y=$(port installed abc)
z='None of the specified ports are installed'
if [[ $y =~ $z ]]
then
  echo 1
else
  echo 0
fi
于 2013-04-21T09:41:40.150 回答
1

另一种方法对诸如遗漏“。”之类的粗心错误不太敏感。

y="`port installed abc`"
if [[ "$y" = *"None of the specified ports are installed"* ]]; 
    then echo 1; 
    else echo 0; 
fi

使用[[ ]]给出了更强大的比较语句。

也代替使用

y="`port installed abc`"

最好写

y=$(port installed abc)

只是在 bash irc 频道上与其他开发人员讨论的一些发现。

于 2013-04-21T09:51:22.540 回答