bash 中的多个 if 条件不起作用

Multiple if condition in bash not working

我编写了以下 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? and What is the difference between the Bash operators [[ vs [ vs ( vs ((?

如果您使用双括号,您可以使用 &&(和)和 ||(或)链接条件。

if [[ "crack" == "crack" && "something/play" == *"play"* ]]
then
     echo "Passed"
else
     echo "Failed"
fi