Home > Back-end >  Expand variable inside curly braces, inside single quotes, inside double quotes
Expand variable inside curly braces, inside single quotes, inside double quotes

Time:04-09

I'm trying to write a bash script that takes a variable and populates it inside a somewhat complex string and I can't figure out how to get it to work.

I have the following bash code..

PWD="foobar"
curl -XPOST "localhost/api/user/bob" -H 'Content-Type: application/json' -d '{"password" : "${PWD}"}

what I want to have happen is obviously this:

curl -XPOST "localhost/api/user/bob" -H 'Content-Type: application/json' -d '{"password" : "foobar"}

but none of the iterations and expansion "tricks" I know seem to work because of the braces and the single and double quotes.

I've tried

$PWD
${PWD} 

Both to no avail.

CodePudding user response:

You need to use double quotes to allow the $PWD to expand. (The braces are irrelevant here.)

-d "{\"password": \"$password\"}"

Better yet, though, use something like jq to generate JSON so that you can be sure everything is quoted correctly without shell interference.

-d "$(jq -n --arg p "$password" '{password: $p}')"
  •  Tags:  
  • bash
  • Related