我正在尝试在 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 请访问此网站: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
有人对如何解决这些错误消息有任何见解吗?我认为这与我编写字符串数组的方式有关,但我无法确定问题所在。
答案1
问题不在于数组的声明,而在于访问元素的方式。看这个帖子
所以,引用SO的原始答案:
for ((i = 0; i < ${#message[@]}; i++))
do
echo "${message[$i]}"
done
在我这边效果很好
(Panki 的建议是正确的,删除 seq 参数周围的反引号。您可以使用$(seq 0 2)
它来代替。但是,这并不能解决问题)
答案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