2

I have the following script:

#!/bin/bash

CONFIG_RECORDER=`aws configservice describe-configuration-recorders`
NAME=$(jq -r ‘.ConfigurationRecorders[].name’ <<<“$CONFIG_RECORDER”)
echo $NAME

I am trying to retrieve the value for name from the following JSON object:

{
"ConfigurationRecorders": [{
    "name": "default",
    "roleARN": "arn:aws:iam::xxxxxxxxxxxx:role/Config-Recorder",
    "recordingGroup": {
        "allSupported": true,
        "includeGlobalResourceTypes": true,
        "resourceTypes": []
    }
}]
}

When running the script, I am getting an error stating that jq could not open the file. That is because I am trying to pass in the result stored in a variable. How can I move past this? Below is the error:

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end 
(Unix shell quoting issues?) at <top-level>, line 1:
‘.ConfigurationRecorders[].name’
jq: 1 compile error
Dave Michaels
  • 847
  • 1
  • 19
  • 51
  • It's 2022 and backticks for command substitution have been obsolescent for 30+ years. See https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming – tripleee Apr 08 '22 at 06:28
  • Separately, [avoid upper case for your private variables.](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization) – tripleee Apr 08 '22 at 06:30
  • Is there a reasons to capture the full JSON to a separate variable? You can avoid that with just `name=$(aws ... | jq ...)` but of course, if you need the JSON for other things, keeping the output in a variable might make sense. – tripleee Apr 08 '22 at 06:31

1 Answers1

2
NAME=$(jq -r '.ConfigurationRecorders[].name' <<<"$CONFIG_RECORDER")

<<< is known as here-string.

-r removes the quotes in the result.

[] in the jq query is necessary as ConfigurationRecorders is a JSON array.

$( … ) is just an other form of command substitution than backticks. I prefer this one as it is more readable to me.

Udo Knop
  • 81
  • 4
  • Thank you for sharing. I am getting an error with the change. I will update the code in the OP. – Dave Michaels Apr 07 '22 at 22:08
  • What are the contents of $CONFIG_RECORDER ? – rr0ss0rr Apr 07 '22 at 22:48
  • The contents of $CONFIG_RECORDER is the JSON object pasted above. – Dave Michaels Apr 08 '22 at 03:15
  • Sorry, that was just a problem of the character set: I entered the answer with an iPad on a German Keyboard, so I got the quotations marks from wrong character set. I corrected my answer with correct quotation marks and tested the code in bash shell. Result: NAME=default – Udo Knop Apr 08 '22 at 06:16