I am trying to make a script that takes some atom feeds and posts them to slack through the Slack API via curl. What I have now works for simple texts, but some of them have double quotes or & characters in them and that seems to annoy slack API as I get an invalid payload error. Here's my script:

rsstail -i 3 -u "http://MY_FEED_URL" -n 0 | while read line;
    # This is just a sample text, it should be ${line}
    data='Something "&" and something do " "';
    payload="payload={\"channel\": \"#my_channel\", \"username\": \"Bot\", \"text\": \"${data}\", \"icon_emoji\": \":ghost:\"}";
    echo ${payload};
    curl \
        -H "Accept: application/json" \
        -X POST \
        -d '${payload}' \

The output of the "echo" is:

payload={"channel": "#my_channel", "username": "Bot", "text": "Something "&" and something do " "", "icon_emoji": ":ghost:"}

I am not advanced in bash scripting and I need a little bit of help. What am I doing wrong ?



You need to url-encode the data, and the easiest way to do this is to get curl to do it for by replacing the -d option by --data-urlencode. Also, you need to use double quotes or the shell will not expand the variable, so we have

curl \
    -H "Accept: application/json" \
    -X POST \
    --data-urlencode "${payload}" \

You can also simplify setting payload= by having part of the string inside single quotes, and part within double quotes, provided there is no space between the parts, as in '...'"..."'...'. So, we get

payload='payload={"channel": "#my_channel", "username": "Bot", "text": "'"${data}"'", "icon_emoji": ":ghost:"}'

You probably need to escape the double quotes in data, perhaps with \, as they will be inside "" in a json string.

data='Something \"&\" and something do \" \"'

If you have read your data from the input into variable line, you can do this replacement with bash:

  • I tried your suggestion and still does not work. If I remove the quotes from the string it does. How do I escape the quotes, since they are within the ${line} variable ? – Comforse Apr 28 '16 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.