kayq
kayq

Reputation: 133

How to execute a command and assign the value to a variable?

How do I return just the Pending value? Right now the command returns the entire json object.

This is what I got so far but am not sure how to filter out to just the Pending value

$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
        },
       ...,
       ...,
    }
}

I want to run the command in an if else block like so:

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

Upvotes: 0

Views: 140

Answers (3)

chepner
chepner

Reputation: 531055

Use the --query argument to filter the response.

get_pending () {
  aws --query 'deploymentInfo.deploymentOverview.Pending' \
    deploy get-deployment --deployment-id "$DEPLOYMENT_ID"
}

if [[ $(get_pending) = 0 ]]; then
    ...
fi

(The shell function is just for readability.)

The --query argument take a JMESPath expression which is used to filter the resulting JSON before returning it to the caller.

Upvotes: 3

Matias Barrios
Matias Barrios

Reputation: 5056

Adding to other answers. If you don't have jq you can do it with 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"

Hope it helps!

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185025

Using :

#!/bin/bash

pending=$(
    aws deploy get-deployment --deployment-id "$DEPLOYMENT_ID" |
    jq -r '.deploymentInfo.deploymentOverview.Pending' 
)

if ((pending == 0)); then
    # do something
fi

Upvotes: 1

Related Questions