如何在bash脚本中将AND和OR条件组合为if条件? [英] How to combine AND and OR condition in bash script for if condition?

查看:1188
本文介绍了如何在bash脚本中将AND和OR条件组合为if条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图结合逻辑与&或在if条件内的bash脚本中.不知何故,我没有获得所需的输出,很难进行故障排除. 我正在尝试验证传递给shell脚本的输入参数中是否没有参数,并且传递的第一个参数是否有效.

I was trying to combine logical AND & OR in a bash script within if condition. Somehow I am not getting the desired output and it is hard to troubleshoot. I am trying to validate the input parameters passed to a shell script for no parameter and the first parameter passed is valid or not.

if [ "$#" -ne 1 ] && ([ "$1" == "ABC" ] || [ "$1" == "DEF" ] || [ "$1" == "GHI" ] || [ "$1" == "JKL" ]) 
then
echo "Usage: ./myscript.sh [ABC | DEF | GHI | JKL]"
exit 1
fi

任何人都可以指出这里出了什么问题吗?

Can anyone point out what is going wrong here?

推荐答案

语句的直接问题是 logic 之一:您可能打算写:

The immediate problem with your statement is one of logic: you probably meant to write:

if [ "$#" -ne 1 ] || ! ([ "$1" = "ABC" ] || [ "$1" = "DEF" ] || [ "$1" = "GHI" ] || [ "$1" = "JKL" ]) 
then
  echo "Usage: ./myscript.sh [ABC | DEF | GHI | JKL]" >&2
  exit 1
fi

也就是说:如果给出的参数超过1个,或者给出的单个参数不等于可接受值之一,则中止.

That is: abort, if either more than 1 argument is given OR if the single argument given does NOT equal one of the acceptable values.

请注意!否定括号中的表达式,并使用字符串相等运算符=(而不是==)的POSIX兼容形式.

Note the ! to negate the expression in parentheses and the use of the POSIX-compliant form of the string equality operator, = (rather than ==).

但是,考虑到您正在使用Bash,则可以使用单个[[ ... ]]条件和Bash的正则表达式匹配运算符=~:

However, given that you're using Bash, you can make do with a single [[ ... ]] conditional and Bash's regular-expression matching operator, =~:

if [[ $# -ne 1 || ! $1 =~ ^(ABC|DEF|GHI|JKL)$ ]] 
then
  echo "Usage: ./myscript.sh [ABC | DEF | GHI | JKL]" >&2
  exit 1
fi

如果不需要POSIX合规性,则[[ ... ]][ ... ]更可取,原因是各种原因. 在当前情况下,$#$1不需要引用,并且||可以在条件条件内 中使用.

If POSIX compliance is not required, [[ ... ]] is preferable to [ ... ] for a variety of reasons. In the case at hand, $# and $1 didn't need quoting, and || could be used inside the conditional.

请注意,上面使用的=~在Bash 3.2+中有效,而在 anubhava有用的答案中使用的隐式extglob语法需要Bash 4.1+;
但是,在较早版本中,您可以显式启用extglob shell选项:shopt -s extglob.(并在此之后恢复其原始值).

Note that =~ as used above works in Bash 3.2+, whereas the implicit extglob syntax used in anubhava's helpful answer requires Bash 4.1+;
in earlier versions you can, however, explicitly enable (and restore to its original value after) the extglob shell option: shopt -s extglob.

这篇关于如何在bash脚本中将AND和OR条件组合为if条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆