繁体   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