在单引号内转义双引号内的单引号

Ale*_*ker 2 bash quoting

我发出一个 curl 命令,理想情况下看起来像这样(请注意,由于缺乏转义,这是不正确的):

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
Run Code Online (Sandbox Code Playgroud)

我是单词中的单引号导致此失败。但是,我不确定如何转义此引用,因为有多个级别的嵌套引用。

作为第二个问题,如果文本字符串中有双引号怎么办?那些人怎么可能逃脱?

我已经阅读了有关转义的内容并查看了其他 SO 帖子(包括如何在单引号字符串中转义单引号?),但我似乎无法找到任何可行的解决方案。链接的帖子讨论了单引号中的单引号,并通过使用双引号解决了这个问题。但是,我的单引号已经是双引号了。所以这个比较复杂。

非常感谢你的帮助。

pah*_*pah 5

一个简单的建议:当有疑问并且没有特殊需要迫使您同时使用单引号和双引号时,只需将引号标准化并转义内部引号:

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
Run Code Online (Sandbox Code Playgroud)

它更干净、更直观。

如果你想真正转义双引号内的单引号:

 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
Run Code Online (Sandbox Code Playgroud)


anu*_*ava 5

没有任何转义等,您可以使用 here-doc 并将其传递给您的curl命令:

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 
Run Code Online (Sandbox Code Playgroud)

@-将使curl从标准输入读取数据。