0

I want to send a message to a slack app in a script:

...
declare -a models=("TR10"
                   "TR100"
                   "TR1000")

for i in "${models[@]}"
do
   #Send Message
   if [ $use_slack_app ]
   then
     message="Starting model $i ($c of $lenght)!"
     data=''\''{"text":"'"$message"'"}'''\'
     echo $data
     curl -X POST -H 'Content-type: application/json' --data $data $slack_app_url
     echo "curl -X POST -H 'Content-type: application/json' --data $data $slack_app_url"
   fi

   #Counter
   ((c=c+1))
done  
...

return of echo $data:

'{"text":"Starting model TR10 (1 of 3)!"}'

curl message:

curl: (3) unmatched close brace/bracket in URL position 5:
3)!"}'
    ^
curl: (6) Could not resolve host: model
curl: (6) Could not resolve host: TR10
curl: (6) Could not resolve host: (1
curl: (6) Could not resolve host: of
invalid_payload

It looks like it sees the string as several parameters, but I don't understand why. If I echo the line out, and run it in the terminal it works. I don't have much experience with bash scripting, so I don't understand what the problem here is.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
big_M
  • 1
  • 1
    Add double quotes around your variables to prevent word splitting and glob matching that is the cause of the error you get. – Léa Gris Jan 24 '22 at 15:40
  • 1
    Adding literal quotes (quotes that are data) cannot substitute for missing syntactic quotes (quotes that are syntax). Using `echo` to see what your command expands to is simply a bad idea in general; you can't tell the difference between `echo "somecommand" "one argument"` and `echo somecommand "one" "argument"`, so it's useless for these purposes; use `set -x` instead when you need to trace your script's execution. – Charles Duffy Jan 24 '22 at 15:45
  • (enabling `set -x` will, in the debug output it emits, ensure that literal quotes are escaped, so they cannot be confused for syntactic quotes; whereas `echo` just writes literal quotes as output and lets syntactic quotes be lost completely). – Charles Duffy Jan 24 '22 at 15:48
  • Thanks. I'll sure have a look at set -x! – big_M Jan 24 '22 at 16:07

1 Answers1

0
  1. Quote the variable expansions to ensure values with spaces are sent as one word: "$var" vs. $var.

  2. Get rid of the single quotes (''\') surrounding $data.

data='{"text":"'"$message"'"}'
curl -X POST -H 'Content-Type: application/json' --data "$data" "$slack_app_url"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Ah, perfect, thank you. I was sure I tried that before without any luck, but apparently I did something wrong. It works now as it should. – big_M Jan 24 '22 at 15:53