Skip to content

Instantly share code, notes, and snippets.

@naveenarun naveenarun/
Last active Jul 22, 2019

What would you like to do?
Bash function for sending a verbose slack message (containing path, command, error code, and custom message) after a process or series of processes exit
# Place this in your .bashrc
# Covers several corner cases such as nested apostrophes, history extraction in screens/subshells, Slack being down, etc.
# Strings to replace with your own credentials:
## {your email address} (1 instance)
## {slack webhook url} (1 instance) (see guide below)
## {your computer name} (2 instances)
# How to set up a Slack webhook (as of Jul 2019):
## Go here:
## Click “incoming webhooks” and turn the slider on
## Click “add new webhook to workspace”, select the “Slackbot” channel, and click Install
## Copy the webhook url that it creates. (You can then replace {slack webhook url} below with that url.)
slack() {
# Get slack message when a command exits
# Example usage: python; slack
# Example usage: python; slack 'job 1 done'; python; slack 'job 2 done';
errorcode=$? # This has to go first; extracts error code
if [ -z "$1" ] # Allows you to attach a message as an argument for multi-step commands
message=" "
message=" with message '$1' "
if [[ $errorcode -eq 0 ]] # Add emoji based on error code
myhistory=$(history | tail -n1 | sed 's/^ *[0-9]* *//g; s/\"/\\\"/g;') # Extract command from history
mydata='{"text":"`[{your computer name}:'$PWD']$ '$myhistory'` exited with status '$errorcode' '$erroremoji'"}'
returnstatus=$(curl -X POST -H 'Content-type: application/json' --data "$mydata" {slack webhook url})
if [[ $returnstatus == 'ok' ]] # Catch case when Slack is down or error message is syntactically invalid
echo 'Success'
echo 'bad request'
$(echo "Slack is down or message is invalid. Process finished at '$PWD'." | mail -s '{your computer name}: Slack is down or requested message is invalid.' '{your email address}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.