1

I'm trying to integrate slack with one of my shell script. I have different conditions, for which the Message part of payload is different.

My script will look like

#!/bin/bash

SLACK_URL='https://hooks.slack.com/services/******
CHANNEL="#channel"
PAYLOAD="'payload={\"channel\": \"${SLACK_CHANNEL}\", \"username\": \"${USER}\", \"text\": \"$MESSAGE\", \"icon_emoji\": \":slack:\"}"

Case 1: condition :

 curl -s -S -X POST --data-urlencode "$PAYLOAD" $SLACK_URL

Case 2: condition

  curl -s -S -X POST --data-urlencode "$PAYLOAD" $SLACK_URL

Case 3: condition

  curl -s -S -X POST --data-urlencode "$PAYLOAD" $SLACK_URL

In each case my Message should be different. I'm trying to avoid declaring payload each time with custom message, looking for an option where I can parse my custom message to my payload. Help please.

  • 1
    Why are all 3 of your "case N: condition" commands exactly the same? – Jeff Schaller Mar 18 '17 at 8:53
0

You can build up your $PAYLOAD piece by piece based on your conditions:

PAYLOAD="payload={"
PAYLOAD="$PAYLOAD\"channel\": \"${SLACK_CHANNEL}\","
PAYLOAD="$PAYLOAD\"username\": \"${USER}\","

case $MESSAGE_TYPE in
    1)
        PAYLOAD="$PAYLOAD \"text\": \"$MESSAGE1\","
        ;;
    2)
        PAYLOAD="$PAYLOAD \"text\": \"$MESSAGE2\","
        ;;
    3)
        PAYLOAD="$PAYLOAD \"text\": \"$MESSAGE3\","
        ;;
esac

PAYLOAD="$PAYLOAD \"icon_emoji\": \":slack:\""
PAYLOAD="$PAYLOAD}"

curl -s -S -X POST --data-urlencode "$PAYLOAD" $SLACK_URL

Alternatively you could have Bash lazily evaluate $PAYLOAD with eval once you've set $MESSAGE correctly.

PAYLOAD_PATTERN='payload={\"channel\": \"${SLACK_CHANNEL}\", \"username\": \"${USER}\", \"text\": \"$MESSAGE\", \"icon_emoji\": \":slack:\"}'
MESSAGE=...
eval "PAYLOAD=\"$PAYLOAD_PATTERN\""

curl -s -S -X POST --data-urlencode "$PAYLOAD" $SLACK_URL

This is a common pattern in shell programming. Note however, that if you any part of the variables expanded as part of $PAYLOAD_PATTERN include untrusted input, using eval in this manner could lead to security problems as an adversary that has the ability to influence any piece of the input arbitrary may use this to gain arbitrary code execution capabilities on the system executing the script.

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.