Created
June 21, 2023 11:55
-
-
Save philpicton/b1e749d1b7ca42501224f5c0381146a7 to your computer and use it in GitHub Desktop.
Bash script to notify Slack channel (via webhook) when a command has completed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # | |
| # Author: Ade Goodyer | |
| # Date: 2023-06-21T11:31 | |
| # Description: Bash script to run command and then notify Slack of success or failure. | |
| # Notes: Create alias or add to PATH to use. | |
| # Requires chmod +x to run. | |
| # | |
| # Usage: notify-slack # usage | |
| # notify-slack ls # slack notification without output | |
| # notify-slack -o ls # slack notification with output | |
| # | |
| if [ $# -lt 1 ]; then | |
| echo "Usage: notify_slack [-o|--output] <command>" | |
| exit 1 | |
| fi | |
| show_output=true | |
| if [ "$1" == "-o" ] || [ "$1" == "--output" ]; then | |
| show_output=true | |
| shift | |
| else | |
| show_output=false | |
| fi | |
| command="$@" | |
| # Record the start time | |
| start_time=$(date +%s.%N) | |
| # Run the provided command and capture the output | |
| output=$(eval "$command") | |
| # Calculate the elapsed time | |
| end_time=$(date +%s.%N) | |
| elapsed_time=$(echo "$end_time - $start_time" | bc) | |
| # Check the exit status of the previous command | |
| if [ $? -eq 0 ]; then | |
| # Command completed successfully | |
| text="Command completed successfully.\n\nCommand: $command" | |
| else | |
| # Command failed | |
| text="Command failed.\n\nCommand: $command" | |
| fi | |
| # Include output in the text if the flag is set to true | |
| if [ "$show_output" = true ]; then | |
| text+="\n\nOutput:\n$output" | |
| fi | |
| text+="\n\nExecution Time: $elapsed_time seconds" | |
| # Send the Slack webhook notification | |
| payload='{"text": "'"$text"'"}' | |
| curl -X POST -H 'Content-type: application/json' --data "$payload" "<slack_webhook_url>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment