4

I need to use the curl command:

curl -d '{ "auth_token": "YOUR_AUTH_TOKEN", "text": "Hey, Look what I can do!" }' \http://localhost:3030/widgets/welcome

in a bash script but instead of "Hey, Look what I can do!" after the "YOUR_AUTH_TOKEN"; I need a variable $p .

This is my first time trying a bash script and read the tutorials on quotes and such but I still am not able to make it work.

kojiro
  • 74,557
  • 19
  • 143
  • 201

2 Answers2

4

The easiest thing to do is to read the data from a here document (a type of dynamically created temporary file), rather then trying to quote the entire thing as a string:

curl -d@- http://localhost:3030/widgets/welcome <<EOF
{ "auth_token": "YOUR_AUTH_TOKEN",
  "text": "$p" }
EOF

If the argument to -d begins with a @, the remainder of the argument is taken as the name of a file containing the data. A file name of - indicates standard input, and the standard input to curl is supplied by the lines between the EOF tokens.

The alternative is to double-quote the string and escape all the embedded double quotes. Yuck.

... -d "{\"auth_token\": \"YOUR_AUTH_TOKEN\", \"text\": \"$p\"}" ...
chepner
  • 497,756
  • 71
  • 530
  • 681
0

An alternative to chepner's very good answer:

data=$( printf '{"auth_token":"YOUR_AUTH_TOKEN","text":"%s"}' "$p" )
curl -d "$data" http://localhost:3030/widgets/welcome
glenn jackman
  • 238,783
  • 38
  • 220
  • 352