Bash IF:多个条件

BDR*_*BDR 6 bash if-statement nested multiple-conditions conditional-statements

我已经尝试让这件事工作几个小时,但我无法让它工作:

if [ "$P" = "SFTP" -a "$PORT" != "22" ] || [ "$P" = "FTPS" && [ "$PORT" != "990" -a "$PORT" != "21" ] ] ; then

有人能帮我吗 ?我知道多个条件可以这样写:

if [ "$P" = "SFTP" ] && [ "$PORT" != "22" ]; then

但我怎样才能像第一个例子一样叠加这些条件呢?

use*_*001 11

不能将表达式嵌套在单括号中。应该这样写:

if [ "$P" = "SFTP" -a "$PORT" != "22" ] || [ "$P" = "FTPS" -a "$PORT" != "990" -a "$PORT" != "21" ] ; then
Run Code Online (Sandbox Code Playgroud)

这可以写成单个表达式:

if [ \( "$P" = "SFTP" -a "$PORT" != "22" \) -o \( "$P" = "FTPS" -a "$PORT" != "990" -a "$PORT" != "21" \) ] ; then
Run Code Online (Sandbox Code Playgroud)

虽然它并不完全兼容所有 shell。

由于您使用的是 bash,因此可以使用双括号使命令更具可读性:

if [[ ( $P = "SFTP" && $PORT != "22" ) || ( $P = "FTPS" && $PORT != "990" && $PORT != "21" ) ]] ; then
Run Code Online (Sandbox Code Playgroud)