Last active
February 20, 2022 01:41
Using Bash trap when a command fails
This file contains 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
#!/usr/bin/env bash | |
set -E | |
function log() { | |
local msg_args=("${@}") | |
local timestamp="$(date +'%Y-%m-%d %T')" | |
declare -u log_level="${msg_args[0]}" | |
local message="${msg_args[@]:1}" | |
echo -e "${timestamp} | ${log_level} | ${msg_args[@]:1}" | |
curl -X POST \ | |
-H 'Content-type: application/json' \ | |
--data "{\"text\":\"${timestamp} | ${log_level} | ${message}\"}" \ | |
## YOUR_WEBHOOK_URL ## | |
} | |
function fatal_log() { | |
declare -a return_codes=("${PIPESTATUS[@]}") | |
local -r array_length="$((${#return_codes[@]}-1))" | |
local -r return_code="${return_codes[array_length]}" | |
log fatal "Script ->${0}<- failed ->${var_on_trap}<- with return code ->${return_code}<- to on ->${BASH_LINENO[0]}:${BASH_COMMAND}<-" | |
exit ${return_code} | |
} | |
trap fatal_log ERR | |
var_on_trap="test001" | |
curl invalid-url | |
ls -l | |
ls -l | grep aaa |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment