2017-05-31 140 views
0

我的脚本的目的是将消息发送到Mattermost服务器。 所以我用卷曲这样做:如何执行包含引号和双引号组合的命令?

#!/bin/bash 
message="This is my message with potentially several quotes in it ..." 
url=http://www.myMatterMostServer.com/hooks/myMattermostKey 
payload="{ \"text\" : \"$message\" }" 
curlCommand="curl --insecure --silent --show-error --header 'Content-Type: application/json' -X POST --data '"$payload"' "$url 
echo -e $curlCommand 
$curlCommand 

echo命令显示的东西,如果我把它复制并直接在终端执行它是可执行的。

但最后一行不正确执行,我有这个控制台:

++ curl --insecure --silent --show-error --header ''\''Content-Type:' 'application/json'\''' -X POST --data ''\''{' '"text"' : '"This' is my message with potentially several quotes in it '..."' '}'\''' http://poclo7.sii24.pole-emploi.intra/hooks/iht8rz8uwf81fgoq9ser8tda3y 
curl: (6) Couldn't resolve host 'application' 
curl: (6) Couldn't resolve host '"text"' 
curl: (6) Couldn't resolve host ':' 
curl: (6) Couldn't resolve host '"This' 
curl: (6) Couldn't resolve host 'is' 
curl: (6) Couldn't resolve host 'my' 
curl: (6) Couldn't resolve host 'message' 
curl: (6) Couldn't resolve host 'with' 
curl: (6) Couldn't resolve host 'potentially' 
curl: (6) Couldn't resolve host 'several' 
curl: (6) Couldn't resolve host 'quotes' 
curl: (6) Couldn't resolve host 'in' 
curl: (6) Couldn't resolve host 'it' 
curl: (6) Couldn't resolve host '..."' 

我试图引号,双引号和$(命令)这么多的组合......请大家帮帮我: - )

+0

也许值得把你的整个有效载荷在一个文件中,并告诉卷曲读取文件中的数据。 https://stackoverflow.com/questions/3007253/send-post-xml-file-using-curl-command-line https://stackoverflow.com/questions/6408904/send-post-request-with-data-specified -in-file-via-curl – GregHNZ

回答

1

变量用于数据而不是代码。见Bash FAQ 50。改为定义一个函数。

curlCommand() { 
    message=$1 
    url=$2 
    payload='{"text": "$message"}' 
    curl --insecure --silent --show-error \ 
     --header 'Content-Type: application/json' \ 
     -X POST --data "$payload" "$url" 
} 

curlCommand "This is my message with potentially several quotes in it ..." http://www.myMatterMostServer.com/hooks/myMattermostKey 

考虑使用jq生成有效载荷,以确保$message内容是正确转义。

payload=$(jq --arg msg "$message" '{text: $msg}') 

或管道jq直接curl输出:

jq --arg msg "$message" '{text: $msg}' | curl ... --data @- ... 
+0

感谢您的回答,但我没有jq支持我...... – OphyTe

+0

您可以使用任何提供JSON库的语言;重点是,你不应该试图通过变量插值手动生成JSON。 – chepner

+0

我终于成功地使用了[Bash FAQ](http://mywiki.wooledge.org/BashFAQ/050)的第六种方法(顺便说一句,真是好东西)。 我也有一个小的CR/LF问题,[这篇文章](https://stackoverflow.com/a/38912470/2145671)帮助我解决。 再次感谢@chepner – OphyTe