![](/img/trans.png)
[英]Multiple AND conditions in bash that work independently based on an OR condition separator?
[英]Bash IF condition with multiple conditions not giving proper result
尝试获取 sonarqube 质量门的 URL 状态并检查状态是否为“OK”,条件是否应该通过,或者如果状态为“ERROR”,则它应该失败。
quality_gatesstatus=$(curl -u $SONAR_TOKEN:https://$SONAR_SERVER/api/qualitygates/project_status?projectKey=$SONAR_PROJECT_KEY\&pullRequest=$SONAR_PR_KEY | grep -Po '"status": *\K"[^"]*"')
echo $SONAR_PR_KEY
echo "Checking the Sonar Quality gate status"
if ("$quality_gatesstatus" != "OK") && ("$quality_gatesstatus" != "NONE")
then
echo "check sonar server and fix the issues: $quality_gatesstatus"
exit 1
else
echo "Quality gate succeeded"
fi
但它不能按照 IF 语句工作,它总是进入 else 条件
该行:
if ("$quality_gatesstatus" != "OK") && ("$quality_gatesstatus" != "NONE")
评估如下(不准确,这是一种启发式):
$quality_gatestatus
被扩展为一些字符串,比如S
S
作为命令执行,带有参数!=
和OK
!=
和NONE
再次执行它。 如果该命令成功,则执行第一个命令块。 否则,执行else
块中的命令。 您看到的错误是因为字符串S
不是可执行命令。 几乎可以肯定你真正想要的是:
if [ "$quality_gatesstatus" != OK ] && [ "$quality_gatesstatus" != NONE ]; then ...
但更有可能你想要一个case
陈述:
case "$quality_gatesstatus" in
OK) ... ;;
NONE) ... ;;
*) ... ;;
esac
shell 的语法有点违反直觉。 不是if condition; then commands; fi
if condition; then commands; fi
if condition; then commands; fi
。 它是if commands; then commands; fi
if commands; then commands; fi
if commands; then commands; fi
。 换句话说,当您编写if [ 5 = 5 ]
时, [
和]
不是shell 语法的一部分。 相反,命令[
使用参数5
、 =
和]
执行。 尽管[
可能是在if
块中执行的最常见的命令,但它可以是任何命令集,并且常见的结构是if grep ...
或if shh ...
或if curl ...
。 查看if cmd1; cmd2; cmd3; then ...
稍微不常见。 if cmd1; cmd2; cmd3; then ...
if cmd1; cmd2; cmd3; then ...
,但你会时不时地看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.