Issue
I am writing a shell script to fire few POST curl requests. I get 400 when I use the below shell script.
#!/bin/sh
ENDPOINT="https://example.com:443/v1/API_NAME"
BODY='{"key1": "value1", "key2": "value2"}'
curl -H "Content-Type: application/json" -v -k -X POST $ENDPOINT -d $BODY
But when i use the body inline it works fine as show below:
curl -H "Content-Type: application/json" -v -k -X POST $ENDPOINT -d '{"key1": "value1", "key2": "value2"}'
The difference in the logs as seen on terminal between both the requests is Content-Length. Somehow for 1st curl request the Content-Length is 1 which i believe is the reason of failure. Can someone help me why the content length is 1 and how to resolve this?
Solution
Use more quotes !
curl -H "Content-Type: application/json" -v -k "$ENDPOINT" -d "$BODY"
The -X POST
is not needed when using -d
switch
Learn how to quote properly in shell, it's very important :
"Double quote" every literal that contains spaces/metacharacters and every expansion:
"$var"
,"$(command "$var")"
,"${array[@]}"
,"a & b"
. Use'single quotes'
for code or literal$'s: 'Costs $5 US'
,ssh host 'echo "$HOSTNAME"'
. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
https://web.archive.org/web/20230224010517/https://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary
Answered By - Gilles Quénot Answer Checked By - Terry (WPSolving Volunteer)