![](/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.