【问题标题】:How to execute a command and assign the value to a variable?如何执行命令并将值分配给变量?
【发布时间】:2019-12-18 18:59:10
【问题描述】:

如何只返回 Pending 值?现在该命令返回整个 json 对象。

这是我目前得到的,但不知道如何过滤到 Pending

$DEPLOYMENT_ID      // env variable

$(aws deploy get-deployment --deployment-id "$DEPLOYMENT_ID")

// returns:
{
    "deploymentInfo": {
        "applicationName": "WordPress_App",
        "status": "Succeeded",
        "deploymentOverview": {
            "Failed": 0,
            "InProgress": 0,
            "Skipped": 0,
            "Succeeded": 1,
            "Pending": 0
        },
       ...,
       ...,
    }
}

我想像这样在 if else 块中运行命令:

if [[ $(aws deploy get-deployment --deployment-id "$DEPLOYMENT_ID") = 0 ]] ;
then
  // do stuff
fi

【问题讨论】:

    标签: linux bash shell unix terminal


    【解决方案1】:

    使用--query 参数过滤响应。

    get_pending () {
      aws --query 'deploymentInfo.deploymentOverview.Pending' \
        deploy get-deployment --deployment-id "$DEPLOYMENT_ID"
    }
    
    if [[ $(get_pending) = 0 ]]; then
        ...
    fi
    

    (shell函数只是为了可读性。)

    --query 参数采用JMESPath expression,用于在将结果 JSON 返回给调用者之前对其进行过滤。

    【讨论】:

      【解决方案2】:

      使用

      #!/bin/bash
      
      pending=$(
          aws deploy get-deployment --deployment-id "$DEPLOYMENT_ID" |
          jq -r '.deploymentInfo.deploymentOverview.Pending' 
      )
      
      if ((pending == 0)); then
          # do something
      fi
      

      【讨论】:

        【解决方案3】:

        添加到其他答案。如果您没有 jq,您可以使用 Python 3:

        value=$( aws deploy get-deployment --deployment-id "$DEPLOYMENT_ID" | python3 -c '
        import sys
        import json
        obj = json.loads("".join(sys.stdin.readlines()))
        print(obj["deploymentInfo"]["deploymentOverview"]["Pending"])
        ' )
        
        [[ "$value" -eq 0 ]] && echo "Value is 0"
        

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 2017-08-12
          • 1970-01-01
          • 1970-01-01
          • 2021-06-11
          • 2011-01-28
          • 2011-01-23
          • 2021-05-24
          • 1970-01-01
          • 2019-10-17
          相关资源
          最近更新 更多