I have the following:

COMMENT="A random comment"  
TEXT_JSON='{"person" : "Jim","comment" : "$COMMENT"}'    
echo "$TEXT_JSON" | jq .  

This prints

  "person": "Jim",  
  "comment": "$COMMENT"  

which is not what I want. How can I interpolate the string here?

  • 1
    In the particular case of jq, you should probably be using its own --arg argument-passing facility, I think – steeldriver Jun 5 '18 at 11:56

You cannot interpolate inside single quotes.

You can put the string in double quotes, then escape the literal double quotes:

COMMENT="A random comment"
TEXT_JSON="{\"person\" : \"Jim\",\"comment\" : \"$COMMENT\"}"
echo $TEXT_JSON | jq .
  "person": "Jim",  
  "comment": "A random comment"  

Or alternatively you can keep the single quotes so you don't have to escape anything, but end the single quotes before the variable, then use double quotes for the variable, then single quotes for the last part of the string:

TEXT_JSON='{"person" : "Jim","comment" : "'"$COMMENT"'"}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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