0

This is my script

#!/bin/bash
set -x
USERNAME="someUser"
curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": $USERNAME, "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json

it just becomes as below, it did not replace $USERNAME with someUser

curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": $USERNAME, "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json

but if i put USERNAME in, it works

curl -H "Content-Type: application/json" -X POST -d '{"auth":{ "client": "someUser", "password": "somePassword" }, "messages": { "UpdateProduct": {} }}' http://someDomain.com/services/json
Dave
  • 5,108
  • 16
  • 30
  • 40
user3552178
  • 2,719
  • 8
  • 40
  • 67

1 Answers1

2

Single quotes don't expand variables. You can use something like

 -d '{"auth":{ "client": '"$USERNAME"', "password"...

but it can still break if the username contains a double quote.

The cleanest way is to use a tool that understands JSON, e.g. jq:

$ USERNAME='"a"' jq '.username|=env.USERNAME' <<< '{"username":"..."}'
{
  "username": "\"a\""
}
choroba
  • 231,213
  • 25
  • 204
  • 289
  • `jq --arg u "$USERNAME" '.username|= $u' <<< '{"username": "..."}'` works as well. (Note you probably don't want the literal double-quotes in the resulting JSON.) – chepner Mar 15 '19 at 12:52
  • I wanted to demonstrate that `jq` properly escapes the doublequotes. – choroba Mar 15 '19 at 12:58