2017-05-31 100 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

相關問題