JSB
JSB

Reputation: 360

bash curl POST request: "-d" option using a variable

I am trying to make a POST request. The following works without any problem;

# Get expected response
curl http://localhost:9020/xxx/xxxx/ -H Content-type:application/json 
-H Accept:application/json -d '{"LED":{ 
"language":"CHINESE"}, "text":"1928年11月22日"}'

However, if I try and set the value for the -d option curl cannot submit the request to the server.

var="{\"LED\":{ \"language\":\"CHINESE\"}, \"text\":\"1928年11月22日\"}"
# No Response
curl http://localhost:9020/xxx/xxxx/ -H Content-type:application/json 
-H Accept:application/json -d $var

Can anyone explain why the latter does not seem to work? I have tried a variety of escape characters, but no luck with that either.

Upvotes: 1

Views: 1449

Answers (1)

janos
janos

Reputation: 124646

You need to double-quote the variable:

curl http://localhost:9020/xxx/xxxx/ -H Content-type:application/json \
-H Accept:application/json -d "$var"

Without the double-quoting, the value is split on spaces, and the shell interprets that as multiple additional arguments to curl, but you need that value to be a single argument. That's what double-quoting will achieve.

Upvotes: 1

Related Questions