Escape single quote within double quote within single quote [duplicate]
Asked Answered
H

2

5

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.

Hesitate answered 10/8, 2016 at 14:25 Comment(3)
@user000001 I edited my post to explain why that post does not solve my problem.Hesitate
Just use an ansi c string $'stuff' and escape the single quotes in it.Wiese
@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/XXXPulse
A
8

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
Armandinaarmando answered 10/8, 2016 at 14:30 Comment(0)
B
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.

Bulger answered 10/8, 2016 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.