0

I am attempting to write a script in bash that monitors certain aspects of a server, and sends a message to slack if it notices that something is wrong. However, I am running into a strange set of error messages that leads me to believe the syntax of my script is a little off. Here is the code in question:

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 

When I run this code, it should send a message to the specified slack group, stating each of the specified lines of text, for example "@channel Please go to this website: www.google.com"

When I run this, I receive the following error messages:

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 

Does anybody have any insights on how to resolve these error messages? I am thinking it has something to do with the way I have written the array of strings, but I can't identify the issue.

2
  • 2
    What happens if you double quote the variable: --data '{"text":"<!channel> '"${message[$j]}"' "}' ?
    – user232326
    CommentedOct 7, 2019 at 14:24
  • 1
    There is no need for backticks around the seq arguments. Use `seq 0 2` and it should work as expected.
    – Panki
    CommentedOct 7, 2019 at 14:34

2 Answers 2

1

The problem is not due to the declaration of the array, but the way you access elements. See This post

So, to quote the original answer from SO:

for ((i = 0; i < ${#message[@]}; i++)) do echo "${message[$i]}" done 

It works fine on my side

(Panki's suggestion is right, remove backtick around seq arguments. You can use $(seq 0 2) instead. However, this does not fix the issue)

    0

    For readability, I would do this:

    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 

      You must log in to answer this question.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.