问题描述
我编写了以下 bash 脚本:
if [ "crack" == "crack" -a "something/play" == *"play"* ];
then
echo "Passed"
else
echo "Failed"
fi
但是,此比较的右侧不起作用。
我注意到,如果我将它与 [[ "something/play" == *"play"* ]]
一起使用,它可以正常工作,但如何在 if 子句中组合两个条件。
解决方法
[
和 [[
之间的区别。第一个是标准命令,其中 =
只是测试相等性。 (请注意,标准运算符是 =
,而不是 ==
。)后者是 ksh 的一个特性,在 Bash 和 Zsh 中受支持,并且那里,=
/==
是模式匹配。此外,您应该避免在 -a
中使用 [ .. ]
,如果您执行类似 [ "$a" = foo -a "$b" = bar ]
和 $a
或 $b
包含 !
.
所以,
$ if [[ "crack" == "crack" && "something/play" == *"play"* ]]; then echo true; fi
true
另见(在 unix.SE 中):Why is [
a shell builtin and [[
a shell keyword? 和 What is the difference between the Bash operators [[ vs [ vs ( vs ((?。
如果您使用双括号,您可以使用 &&
(和)和 ||
(或)链接条件。
if [[ "crack" == "crack" && "something/play" == *"play"* ]]
then
echo "Passed"
else
echo "Failed"
fi