Skip to content

Instantly share code, notes, and snippets.

@LozanoMatheus
Last active February 20, 2022 01:41
Show Gist options
  • Save LozanoMatheus/6804002f31dd8c85b26e69c635e3a2ea to your computer and use it in GitHub Desktop.
Save LozanoMatheus/6804002f31dd8c85b26e69c635e3a2ea to your computer and use it in GitHub Desktop.
Using Bash trap when a command fails
#!/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