Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bug trying to preserve linebreak in curl request in bash

I have the following script that works perfectly:

payload='{"index":{}}'$'\n''{"name":"Samuel"}'
echo "$payload" > tmp.json
curl -X POST  "http://my.api.com/" \
  -H "Content-Type: application/json" \
  --data-binary @./tmp.json

I get a success response from my.api.com and I confirmed the entry made it into the database.

I don’t like that I am writing a tmp.json to disk. I prefer to send the payload variable as is directly to the curl statement. So I tried something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

payload='{"index":{}}'$'\n''{"name":"Samuel"}'
curl -X POST  "http://my.api.com/" \
  -H "Content-Type: application/json" \
  --data @- << echo "$payload"

But I get an error response from my.api.com saying there are line break issues and syntax issues. What Can I do to avoid writing the payload variable to disk?

I’ve tried many other things like:

--data "$payload"
--data `$payload`
--data @<(echo "$payload")
...etc...

But none of these are working.

>Solution :

<< is for here documents:

curl ... <<EOF
$payload
EOF

You want either a process substitution

curl ... < <(echo "$payload")

or a here string

curl ... <<< "$payload"

But if you already have the payload in a parameter, you don’t need @- anymore:

curl ... --data "$payload"

I’m not sure why that would be producing the error you claim.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading