Shell 命令到 json 输出中的 return 值

Shell command to return value in json output

如何使用shell命令return一个特定值? 在下面的示例中,我想查询 return "StackStatus" 的值,即 "CREATE_COMPLETE"

命令如下:

aws cloudformation describe-stacks --stack-name stackname

这是输出:

{
        "Stacks": [{
            "StackId": "arn:aws:cloudformation:ap-southeast-2:64560756805470:stack/stackname/8c8e3330-9f35-1er6-902e-50fae94f3fs42",
            "Description": "Creates base IAM roles and policies for platform management",
            "Parameters": [{
                "ParameterValue": "64560756805470",
                "ParameterKey": "PlatformManagementAccount"
            }],
            "Tags": [],

            "CreationTime": "2016-10-31T06:45:02.305Z",
            "Capabilities": [
                "CAPABILITY_IAM"
            ],
            "StackName": "stackname",
            "NotificationARNs": [],
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        }]
    }

aws cli 支持--query 选项来获取部件。此外,您还可以通过管道连接到另一个命令行工具 jq 来执行类似的查询。

但在 aws 符号中得到第一个结果:

aws cloudformation describe-stacks --stack-name stackname --query 'Stacks[0].StackStatus' --output text

根据上面的输出,Stacks是一个对象数组(一个key/value),因此需要[0] 获取数组的第一个元素,然后 .StackStatus 是此对象中包含字符串作为值的键。 --output text 只是将输出呈现为简单的文本值,而不是 json 外观的对象。

根据 Charles 评论编辑。