Search code examples
curlslack

Formatting slack message posted from shell script


I have a shell program which write multiline output to a variable called "$text" which outputs as below on terminal.

echo "$text"

==============================================
Oracle Host: xxxxxxxxx
==============================================
orcl:
Database UP -- OK
Listener UP -- OK
Database Read&Write Mode -- OK
Instance Status -- OK
Instance Login Allowed -- OK
---------------------------------------------
orcltest:
Database UP -- OK
Listener UP -- OK
Database Read&Write Mode -- OK
Instance Status -- OK
Instance Login Allowed -- OK
---------------------------------------------

Now to trying to post this as above output in slack channel, so trying to read the lines from above variable with code below:

while IFS= read -r line; do
#printf '%s\n' "$line"
text="$text$line\n"
done <<< "$text"
escapedText=$(echo $text | sed 's/"/\\"/g; s/'\''/\\'\''/g' )
json="{\"channel\": \"#$channel\", \"text\": \"$escapedText\"}"
curl -X POST --data-urlencode "payload=$json" https://hooks.slack.com/services/xxxxx/xxxx/xxxxx"

its showing error like:

missing_text_or_fallback_or_attachments

but in above code I guess while loop is not working properly...is that correct way of reading multi line variable and pass on to payload in curl statement


Solution

  • The escapedText=$(echo $text | sed 's/"/\\"/g; s/'\''/\\'\''/g' ) can cause problems. The $text should be quoted when you do not want the shell to interpret the data (eat spaces and newlines, get confused by special characters).

    The loop reading from the var is not needed and might give problems when the last character in the var is not a \n. The read command only reads "complete lines", anything after the last \n is ignored.
    This problem is also possible when reading from a file. Most times when a file has been created (using vi or echo "Something" > file) the file will be created with a closing \n. The loop, filling a var $text with the contents of $text is not needed.