Skip to content

Instantly share code, notes, and snippets.

@rawiriblundell
Last active April 27, 2021 21:49
Show Gist options
  • Save rawiriblundell/2dab6903848f73641652a8e95e872dcb to your computer and use it in GitHub Desktop.
Save rawiriblundell/2dab6903848f73641652a8e95e872dcb to your computer and use it in GitHub Desktop.
# Get the top level PID and setup a trap so that we can call die() within subshells
trap "exit 1" TERM
_self_pid="${$}"
export _self_pid
# Function to print an error message and exit
die() {
if [ -t 0 ]; then
printf '\e[31;1m====>%s\e[0m\n' "${0}:(${LINENO}): ${*}" >&2
else
printf -- '====>%s\n' "${0}:(${LINENO}): ${*}" >&2
fi
# Send a TERM signal to the top level PID, this is trapped and exit 1 is forced
kill -s TERM "${_self_pid}"
}
Or in a terser form:
# shellcheck disable=SC2059
die() {
[ -t 0 ] && _diefmt='\e[31;1m====>%s\e[0m\n'
printf "${_diefmt:-====>%s\n}" "${0}:(${LINENO}): ${*}" >&2
# Send a TERM signal to the top level PID, this is trapped and exit 1 is forced
kill -s TERM "${_self_pid}"
}
With datestamps and [ERROR] tags:
die() {
if [ -t 0 ]; then
printf '\e[31;1m====>[%s] %s [ERROR]: %s\e[0m\n' "$(date +%s)" "${0}:${LINENO}" "${*}" >&2
else
printf -- '====>[%s] %s [ERROR]: %s\n' "$(date +%s)" "${0}:${LINENO}" "${*}" >&2
fi
# Send a TERM signal to the top level PID, this is trapped and exit 1 is forced
kill -s TERM "${_self_pid}"
}
@rawiriblundell
Copy link
Author

Making public

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment