【问题标题】:Escape single quote within double quote within single quote [duplicate]单引号内双引号内转义单引号[重复]
【发布时间】:2016-12-17 00:02:31
【问题描述】:

我正在发出一个理想情况下看起来像这样的 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

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

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

我已阅读有关转义的信息并查看了其他 SO 帖子(包括 How to escape single-quotes within single-quoted strings?),但我似乎无法找到任何解决方案。链接的帖子讨论了单引号中的单引号,并通过使用双引号解决了该问题。但是,我的单引号已经在双引号中。所以这更复杂。

非常感谢您的帮助。

【问题讨论】:

  • @user000001 我编辑了我的帖子以解释为什么该帖子不能解决我的问题。
  • 只需使用 ansi c 字符串 $'stuff' 并转义其中的单引号。
  • @Alex:重新编辑,没有区别。就 bash 而言,单引号内的双引号只是另一个字符。所以这样的事情应该可以工作: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

标签: bash quoting


【解决方案1】:

没有任何转义等,您可以使用 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 

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

【讨论】:

    【解决方案2】:

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

    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
    

    它更简洁直观。

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

     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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 2019-12-13
      相关资源
      最近更新 更多