Search code examples
bashquoting

Escape single quote within double quote within single quote


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.


Solution

  • 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