Bash – Fix cURL POST Script Adding Single Quotes to Variables with Spaces

bashcurllinuxshell-scripting

The first 3 variables will always have no spaces. The fourth "slacksitename" has spaces

ip=“x.x.x.x"
record_name=“demo.xyz"
slackuri:”WEBHOOK"
slacksitename:”123 Main St"

When called with cURL

curl -X POST -H 'Content-type: application/json' --data '{"text":"’$slacksitename': '$ip' '$record_name' DDNS updated.”}’ $slackuri

The output is as follows:

curl -X POST -H 'Content-type: application/json' --data '{"text":"123' Main 'St: x.x.x.x demo.xyz DDNS updated."}' https://hooks.slack.com/services/……..
curl: (6) Could not resolve host: Main
curl: (3) unmatched close brace/bracket in URL position 59:
St: x.x.x.x demo.xyz DDNS updated."

Would anyone know why it's adding the single quotes to 123' Main 'St? And how I'd get that to treat the entire variable as one string instead of splitting it (which is what I think it's doing)?

Thanks

UPDATE: Solved^^

Follow Up:

This probably falls along the same lines of the original quetion:

I have a variable that is a JSON output that I want to send via cURL. I'm Assuming the issue is quotations again but the JSON output may change (Number of quotes). Is there any way of sending this raw data with cURL in the message with a new line? Thanks

DUMPING RESULTS:\n{"result":{"id":"ppbkbz2ezmxen11vvpi65chsro1vki5y","zone_id":"unuM0sR1gSrQ37r9fGC1sYKFZOP0DzJM","zone_name":"demo.xyz","name":"1.demo.xyz","type":"A","content":"x.x.x.x","proxiable":true,"proxied":false,"ttl":1,"locked":false,"meta":{"auto_added":false,"managed_by_apps":false,"managed_by_argo_tunnel":false,"source":"primary"},"created_on":"2020-06-14T19:13:57.096688Z","modified_on":"2021-10-16T16:57:49.269274Z"},"success":true,"errors":[],"messages":[]}."

Best Answer

You're using unquoted variables in bash and look surprised that word splitting happens. This is what's supposed to happen.

You also have non-standard quotes in your question that I'll assume are because of automatic formatting. But note that " is not the same as and ' is not the same as ʼ.

curl -X POST -H 'Content-type: application/json' --data '{"text":"’$slacksitename': '$ip' '$record_name' DDNS updated.”}’ $slackuri

In your command line, you're quoting {"text":" and appending the unquoted content of $slacksitename to it, which means word splitting will take place on it. The end result will be 3 separate arguments: {"text":"123, Main, St. The third argument will be concatenated with : which will itself be concatenated with the content of the unquoted $ip so we're any spaces present in that variable, the same would happen.

This is essentially bash 101, quote your variables unless you know what you're doing.