如何在bash脚本中的curl调用中使用变量
我有一个简单的任务,我已经花了几个小时试图弄清楚如何在bash脚本中的curl调用中使用变量:如何在bash脚本中的curl调用中使用变量,bash,shell,curl,Bash,Shell,Curl,我有一个简单的任务,我已经花了几个小时试图弄清楚如何在bash脚本中的curl调用中使用变量: message="Hello there" curl -X POST -H 'Content-type: application/json' --data '{"text": "${message}"}' 这是输出${message},因为它在一个单引号内。如果我更改引号并将双外置和单内置,它会显示command not found:Hello,然后显示command not found:there
message="Hello there"
curl -X POST -H 'Content-type: application/json' --data '{"text": "${message}"}'
这是输出${message},因为它在一个单引号内。如果我更改引号并将双外置和单内置,它会显示command not found:Hello,然后显示command not found:there
如何使其工作?变量不在单引号内展开。使用双引号重写:
curl -X POST -H 'Content-type: application/json' --data "{\"text\": \"${message}\"}"
请记住,双引号中的双引号必须转义
另一种变化可能是:
curl -X POST -H 'Content-type: application/json' --data '{"text": "'"${message}"'"}'
这一个从单引号中分离出来,将${message}
括在双引号中以防止分词,然后以另一个单引号字符串结束。即:
... '{"text": "'"${message}"'"}'
^^^^^^^^^^^^
single-quoted string
... '{"text": "'"${message}"'"}'
^^^^^^^^^^^^
double-quoted string
... '{"text": "'"${message}"'"}'
^^^^
single-quoted string
另一篇文章(和)正确地指出单引号可以防止变量扩展,而健壮的解决方案是使用JSON工具,如jq
:
message="Hello there"
curl -X POST -H 'Content-type: application/json' \
--data "$(jq -n --arg var "$message" '.text = $var')"
即使
$message
包含引号和反斜杠,这也能正常工作,而仅仅将其注入JSON字符串可能会导致数据损坏、JSON无效或安全问题。该死!我知道事情很简单!:)非常感谢。我会尽快接受答案。我更喜欢第二个。事实上我离那个很近。我的一个版本看起来像这样:“${message}'”。因此,我只需要内部双引号,但这个错误对获取这方面的提示没有多大帮助。更好的是,只需将jq
的输出管道连接到curl
,并使用@-
作为--data
的参数。这消除了一层引用。