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
3
  • It's 2022 and backticks for command substitution have been obsolescent for 30+ years. See stackoverflow.com/questions/4708549/… Commented Apr 8, 2022 at 6:28
  • Separately, avoid upper case for your private variables. Commented Apr 8, 2022 at 6: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. Commented Apr 8, 2022 at 6:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for sharing. I am getting an error with the change. I will update the code in the OP.
What are the contents of $CONFIG_RECORDER ?
The contents of $CONFIG_RECORDER is the JSON object pasted above.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.