简体   繁体   中英

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

although is is not fully compatible with all shells.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM