0

I am saving output of my command in a variable and using it in other command

instance_id=$(aws ec2 describe-instances --query Reservations[*].Instances[*].[InstanceId] --filters "Name=tag:staging,Values=staging")

I get this output [ [ [ "i-09140824c1b7f9ea7" ] ] ]

How to I remove brackets from the output and use it in the variable in this command

aws ec2 associate-address --instance-id $instance_id --allocation-id allocid

I am new to bash so any help would be appreciated.

6
  • Your output is JSON. Use a JSON parser like jq. Commented Sep 12, 2019 at 11:47
  • 2
    you could use --output text no?
    – Rorschach
    Commented Sep 12, 2019 at 11:51
  • 1
    Ahh -- telling aws to emit plaintext output would be even better. Commented Sep 12, 2019 at 11:52
  • 1
    @daveMiller, ...btw, note that you should also put quotes around "$instance_id" in your final command. Basically, every expansion should be quoted unless you have a very explicit reason not to; see shellcheck.net warning SC2086. Commented Sep 12, 2019 at 11:53
  • 1
    @jenesaisquoi, ...I don't know AWS tooling well enough to stand by such an answer and support it if I added it myself -- maybe you could add an explicit answer to that effect? It's definitely good advice. Commented Sep 12, 2019 at 12:01

1 Answer 1

3

You can extract the value and decode it from JSON to plain text with the following:

instance_id_json='[ [ [ "i-09140824c1b7f9ea7" ] ] ]'
instance_id=$(jq -r '.[][][]' <<<"$instance_id_json")

Consider changing your original code to:

instance_id_json=$(aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]' --filters 'Name=tag:staging,Values=staging')

...note that we're putting the query in quotes (since it has glob characters), not just the filter (and since the filter is intended to be literal text with no expansions, we're defaulting to single-quotes rather than double as a matter of form).

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.