4

I am issuing a curl command that would ideally look like this (note that this is incorrect due to lack of escaping):

curl -X POST --data-urlencode 'payload={"channel": "@somebody", "text": "I'm sending you a test message. Let me know if you get it."}' https://hooks.slack.com/services/XXX

The single quote in the word I'm causes this to fail. However, I am unsure how to escape this quote since there are several levels of nested quotes.

As a second question, what if there were double quotes inside the text string? How could those be escaped?

I have read about escaping and looked at other SO posts (including How to escape single-quotes within single-quoted strings?), but I can't seem to get any solutions to work. The linked post talks about single quotes in single quotes and solves that problem by using double quotes. However, my single quote is already in double quotes. So this is more complicated.

Thanks so much for your help.

Community
  • 1
  • 1
Alex Parker
  • 1,533
  • 3
  • 16
  • 38
  • 1
    @user000001 I edited my post to explain why that post does not solve my problem. – Alex Parker Aug 10 '16 at 14:33
  • Just use an ansi c string `$'stuff'` and escape the single quotes in it. – 123 Aug 10 '16 at 14:34
  • @Alex: Re the edit, there is no difference. As far as bash is concerned, the double quote inside single quotes is just another character. So something like this should work: `curl -X POST --data-urlencode 'payload={"channel": "@somebody", "text": "I'\''m sending you a test message. Let me know if you get it."}' https://hooks.slack.com/services/XXX` – user000001 Aug 10 '16 at 14:34

2 Answers2

7

A simple advice: when in doubt and no special needs that force you to use both single and double quotes, just normalize the quotes and escape the inner ones:

curl -X POST --data-urlencode "payload={\"channel\": \"@somebody\", \"text\": \"I'm sending you a test message. Let me know if you get it.\"}" https://hooks.slack.com/services/XXX

It's cleaner and intuitive.

If you want to really escape the single quote inside double quotes:

 curl -X POST --data-urlencode 'payload={"channel": "@somebody", "text": "I'\''m sending you a test message. Let me know if you get it."}' https://hooks.slack.com/services/XXX
pah
  • 4,700
  • 6
  • 28
  • 37
6

Without any escaping etc you can use here-doc and pass it to your curl command:

cat<<-'EOF' | curl -X POST --data-urlencode @- https://hooks.slack.com/services/XXX
payload={"channel": "@somebody", "text": "I'm sending you a test message. Let me know if you get it."}
EOF 

Here @- will make curl read data from stdin.

anubhava
  • 761,203
  • 64
  • 569
  • 643