Skip to content

Instantly share code, notes, and snippets.

@mehmetahsen
Created May 7, 2021 20:46
Show Gist options
  • Save mehmetahsen/5137fb130e64927a13fdcf42da09cb11 to your computer and use it in GitHub Desktop.
Save mehmetahsen/5137fb130e64927a13fdcf42da09cb11 to your computer and use it in GitHub Desktop.
Poor man's Telegram notifier
#!/bin/bash
# Bash Import/Source script
# Prints/Sends start/error/end messages
set -o pipefail
set -o errtrace
# Have below variables set
TELEGRAM_BOT_TOKEN=''
TELEGRAM_CHAT_ID=''
script_name=`basename "$0"`
notify() {
local -r message_text="${@:1}"
echo "$message_text"
curl --silent "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAT_ID}&text=${message_text}" 2>&1 > /dev/null
}
report_error() {
declare -a return_codes=("${PIPESTATUS[@]}")
local -r array_length="$((${#return_codes[@]}-1))"
local -r return_code="${return_codes[array_length]}"
local -r error_message="ERROR in ${script_name} at line ${BASH_LINENO[0]} command ${BASH_COMMAND} with exit code ${return_code}"
notify $error_message
exit 99
}
report_end() {
local -r end_message="$script_name ended."
notify $end_message
}
notify "$script_name started."
trap report_error ERR
trap report_end EXIT
#!/bin/bash
. telegram.sh
echo `date --utc`
bash -c 'echo oops; exit 111'
echo `date --utc`
exit 0
# What we get on Telegram:
# zample.sh started.
# ERROR in zample.sh at line 6 command bash -c 'echo oops; exit 111' with exit code 111
# zample.sh ended.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment