如何在 bash 脚本中的 curl 调用中使用变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40852784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use a variable in curl call within bash script
提问by Bravi
I have this simple task and I've spent a few hours already trying to figure out how can I use a variable inside a curl call within my bash script:
我有这个简单的任务,我已经花了几个小时试图弄清楚如何在我的 bash 脚本中的 curl 调用中使用变量:
message="Hello there"
curl -X POST -H 'Content-type: application/json' --data '{"text": "${message}"}'
This is outputting ${message}, literally because it's inside a single quote. If I change the quotes and put double outside and single inside, it says command not found: Hello and then command not found: there.
这是输出 ${message},字面上是因为它在单引号内。如果我更改引号并将 double 放在外面,single 在里面,它会说找不到命令:你好,然后找不到命令:那里。
How can I make this work?
我怎样才能使这项工作?
回答by janos
Variables are not expanded within single-quotes. Rewrite using double-quotes:
变量不在单引号内展开。使用双引号重写:
curl -X POST -H 'Content-type: application/json' --data "{\"text\": \"${message}\"}"
Just remember that double-quotes within double-quotes have to be escaped.
请记住,必须对双引号中的双引号进行转义。
Another variation could be:
另一种变化可能是:
curl -X POST -H 'Content-type: application/json' --data '{"text": "'"${message}"'"}'
This one breaks out of the single quotes, encloses ${message}
within double-quotes to prevent word splitting, and then finishes with another single-quoted string. That is:
这个从单引号中跳出来,用${message}
双引号括起来以防止分词,然后以另一个单引号字符串结束。那是:
... '{"text": "'"${message}"'"}'
^^^^^^^^^^^^
single-quoted string
... '{"text": "'"${message}"'"}'
^^^^^^^^^^^^
double-quoted string
... '{"text": "'"${message}"'"}'
^^^^
single-quoted string
回答by that other guy
While the other post (and shellcheck) correctly points out that single quotes prevent variable expansion, the robust solution is to use a JSON tool like jq
:
虽然另一篇文章(和shellcheck)正确地指出单引号会阻止变量扩展,但可靠的解决方案是使用 JSON 工具,例如jq
:
message="Hello there"
curl -X POST -H 'Content-type: application/json' \
--data "$(jq -n --arg var "$message" '.text = $var')"
This works correctly even when $message
contains quotes and backslashes, while just injecting it in a JSON string can cause data corruption, invalid JSON or security issues.
即使$message
包含引号和反斜杠,这也能正常工作,而仅将其注入 JSON 字符串可能会导致数据损坏、无效的 JSON 或安全问题。