簡體   English   中英

如何在 shell 腳本中使用帶有某些條件的循環

[英]how to use loop with some conditions in shell script

我需要多次運行curl命令,每次都檢查結果。 我使用 for 循環從curl ,並且我想在達到正確狀態時退出循環。

第一次運行curl命令時,它會顯示這個 output:

{
  "name": "organizations/org_name/operations/long_running_operation_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.apigee.v1.OperationMetadata",
    "operationType": "INSERT",
    "targetResourceName": "organizations/org_name",
    "state": "IN_PROGRESS"
  }
}

完成需要時間,這就是為什么它說IN_PROGRESS 大約需要 30 到 60 秒,如果我們在 30 到 60 秒后運行相同的curl命令,那么它將在下面顯示 output:

{
  "error": {
    "code": 409,
    "message": "org graceful-path-310004 already associated with another project",
    "status": "ALREADY_EXISTS",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.RequestInfo",
        "requestId": "11430211642328568827"
      }
    ]
  }
}

這是我到目前為止的腳本:

test=$(curl -H "Authorization: Bearer $TOKEN" -X POST -H "content-type:application/json" \
  -d '{
    "name":"'"$ORG_NAME"'",
    "displayName":"'"$ORG_DISPLAY_NAME"'",
    "description":"'"$ORGANIZATION_DESCRIPTION"'",
    "runtimeType":"'"$RUNTIMETYPE"'",
    "analyticsRegion":"'"$ANALYTICS_REGION"'"
  }' \
          "https://apigee.googleapis.com/v1/organizations?parent=projects/$PROJECT_ID" | jq '.error.status')
echo $test
while [ $test = "ALREADY EXISTS" ||  $test != "IN_PROGRESS"  ]
do
        echo $test
        echo "Organization is creating"
        test=$(curl -H "Authorization: Bearer $TOKEN" -X POST -H "content-type:application/json" \
  -d '{
    "name":"'"$ORG_NAME"'",
    "displayName":"'"$ORG_DISPLAY_NAME"'",
    "description":"'"$ORGANIZATION_DESCRIPTION"'",
    "runtimeType":"'"$RUNTIMETYPE"'",
    "analyticsRegion":"'"$ANALYTICS_REGION"'"
  }' \
          "https://apigee.googleapis.com/v1/organizations?parent=projects/$PROJECT_ID" | jq '.error.status')
done
echo "exit from loop"

要減少重復代碼,請使用函數。

此外,使用jq生成json 的最佳實踐——它將安全地處理數據中的任何嵌入引號:

json() {
    jq  --arg name "$ORG_NAME" \
        --arg displayName "$ORG_DISPLAY_NAME" \
        --arg description "$ORGANIZATION_DESCRIPTION" \
        --arg runtimeType "$RUNTIMETYPE" \
        --arg analyticsRegion "$ANALYTICS_REGION" \
        --null-input --compact-output \
        '$ARGS.named'
}

errorStatus() {
    curl -H "Authorization: Bearer $TOKEN" \
         -X POST \
         -H "content-type:application/json" \
         -d "$(json)" \
          "${URL}?parent=projects/$PROJECT_ID" \
    | jq -r '.error.status'
}

while true; do
    status=$(errorStatus)
    [ "$status" = "ALREADY EXISTS" ] && break
done

echo "exit from loop"

while true; do some code; condition && break; done while true; do some code; condition && break; done while true; do some code; condition && break; done位是do-while循環的 bash 版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM