Bash IF : multiple conditions

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 13:09:27

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18974788/bash-if-multiple-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!