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

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

问题描述

我试图结合逻辑 AND &OR 在 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?

推荐答案

你的陈述的直接问题是一个逻辑:你可能打算写:

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 不需要引用,并且 || 可以在 inside 使用> 有条件的.

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 的有用答案 需要 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 脚本中为 if 条件组合 AND 和 OR 条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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