Bash
在 bash 中使用帶有空格的字元串數組 - 錯誤消息“curl:無法解析主機”
我正在嘗試在 bash 中編寫一個腳本來監視伺服器的某些方面,並在它發現有問題時向 slack 發送消息。但是,我遇到了一組奇怪的錯誤消息,這讓我相信我的腳本的語法有點不對勁。這是有問題的程式碼:
message=("Please go to this website: www.google.com" "Please go to this website: www.github.com" "Please go to this website: www.wikipedia.com") for j in seq `0 2`; do curl -X POST -H 'Content-type: application/json' --data '{"text":"<!channel> '${message[$j]}' "}' https://hooks.slack.com/services/AN_ID/ANOTHER_ID/SOME_ID# Slack with channel mention done
當我執行此程式碼時,它應該向指定的 slack 組發送一條消息,說明指定的每一行文本,例如“@channel Please go to this website: www.google.com”
當我執行它時,我收到以下錯誤消息:
curl: (6) Could not resolve host: go curl: (6) Could not resolve host: to curl: (6) Could not resolve host: this curl: (6) Could not resolve host: website: curl: (3) [globbing] unmatched close brace/bracket in column 34 invalid_payloadcurl: (6) Could not resolve host: go curl: (6) Could not resolve host: to curl: (6) Could not resolve host: this curl: (6) Could not resolve host: website: curl: (3) [globbing] unmatched close brace/bracket in column 33
有人對如何解決這些錯誤消息有任何見解嗎?我認為這與我編寫字元串數組的方式有關,但我無法確定問題所在。
問題不在於數組的聲明,而在於您訪問元素的方式。看到這篇文章
因此,引用 SO 的原始答案:
for ((i = 0; i < ${#message[@]}; i++)) do echo "${message[$i]}" done
它在我這邊工作正常
(Panki 的建議是正確的,刪除 seq 參數周圍的反引號。您可以
$(seq 0 2)
改用。但是,這並不能解決問題)
為了可讀性,我會這樣做:
messages=( "first" "second" ... ) curl_opts=( -X POST -H 'Content-type: application/json' ) data_tmpl='{"text":"<!channel> %s "}' url=https://hooks.slack.com/services/... for msg in "${messages[@]}"; do curl "${curl_opts[@]}" --data "$(printf "$data_tmpl" "$msg")" "$url" done