Bash IF:多个条件 [英] Bash IF : multiple conditions
问题描述
我一直在尝试使此功能工作几个小时,但我无法使其正常工作:
I've been trying to make this thing work for a couple of hours but I can't get it to work :
if [ "$P" = "SFTP" -a "$PORT" != "22" ] || [ "$P" = "FTPS" && [ "$PORT" != "990" -a "$PORT" != "21" ] ] ; then
有人可以帮助我吗?我知道可以这样写多个条件:
Can someone help me ? I know that multiple conditions can be written like this :
if [ "$P" = "SFTP" ] && [ "$PORT" != "22" ]; then
但是如何像我的第一个示例中那样概括这些条件?
but how can I imbricate theses conditions like in my first example?
推荐答案
您不能将表达式嵌套在单括号中.应该这样写:
You can't nest expressions in single brackets. It should be written like this:
if [ "$P" = "SFTP" -a "$PORT" != "22" ] || [ "$P" = "FTPS" -a "$PORT" != "990" -a "$PORT" != "21" ] ; then
这可以写为单个表达式,如下:
This can be written as a single expressions as:
if [ \( "$P" = "SFTP" -a "$PORT" != "22" \) -o \( "$P" = "FTPS" -a "$PORT" != "990" -a "$PORT" != "21" \) ] ; then
尽管不是与所有shell完全兼容.
although is is not fully compatible with all shells.
由于您正在使用bash,因此可以使用双括号使命令更具可读性:
Since you are using bash, you can use double brackets to make the command more readable:
if [[ ( $P = "SFTP" && $PORT != "22" ) || ( $P = "FTPS" && $PORT != "990" && $PORT != "21" ) ]] ; then
这篇关于Bash IF:多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!