h0bb5
h0bb5

Reputation: 529

How to concatenate jq with variables?

I have a json object I am reading with jq and trying to write some properties with local variables.

I am setting local variable in my shell script like so:

LOCATION_NAME="stag5"
DOMAIN_LOCATION="example.io"

I am then building out the following variable:


echo "Build New ID"

DOMAIN_NAME_BUILT="$LOCATION_NAME.$DOMAIN_LOCATION.s3-website.us-east-2.amazonaws.com"


I am trying to read my distconfig.json file and set the properties with the above variables.

tmp=$(mktemp)
jq '.Origins.Items[0].DomainName = "$DOMAIN_NAME_BUILT"' distconfig.json > "$tmp" && mv "$tmp" distconfig.json

The command is working, but it is passing in the variable as a string to my new json file. So when I view the property in the new created json file it is being saved as "$DOMAIN_NAME_BUILT" instead of stag5.example.io.s3-website.us-east-2.amazonaws.com

How can I instead of passing the string pass the variable for $DOMAIN_NAME_BUILT and write it to the new json file

Upvotes: 2

Views: 3187

Answers (1)

chepner
chepner

Reputation: 532418

Use the --argjson option instead of parameter interpolation.

jq --argjson dnb "$DOMAIN_NAME_BUILT" \
    '.Origins.Items[0].DomainName = $dnb' distconfig.json > "$tmp" &&
  mv "$tmp" distconfig.json

(Your immediate issue is that parameter expansion doesn't occur inside single quotes, but building a static filter that takes an argument is safer than building a filter dynamically.)

Upvotes: 4

Related Questions