按预期运行:-
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.
这里的主要区别是$y
是由port installed abc
命令动态确定的。但为什么这会影响我的比较呢?
请注意。
<>之前指定的端口没有安装之前不等于<>之前指定的端口没有安装。^/就在那儿——之前
另一个选择
y=$(port installed abc)
z='None of the specified ports are installed'
if [[ $y =~ $z ]]
then
echo 1
else
echo 0
fi
一种对粗心错误不那么敏感的替代方法,比如遗漏了一个"。"
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频道上与其他开发人员讨论的一些发现。