Skip to content

Instantly share code, notes, and snippets.

@dereckmartin
Last active April 6, 2022 02:53
Show Gist options
  • Save dereckmartin/345f6ba3046dd20d340d1a8d36ab9c6f to your computer and use it in GitHub Desktop.
Save dereckmartin/345f6ba3046dd20d340d1a8d36ab9c6f to your computer and use it in GitHub Desktop.
BASH trap gist
#!/usr/bin/env bash
##
# Trap Setup
#
# This trap setup allows for a ERRNO_MSG to be provided in any function
##
trap 'chute ${LINENO} $? "${ERRNO_MSG}"' ERR
function chute() {
echo "[ERROR] Line: ${1} Code: ${2} Message: ${3}"
exit 1
}
function test_trap() {
if [ -n "$1" ]; then
echo "Success"
return 0
fi
ERRNO_MSG="$FUNCNAME() requires 1 argument"
return 1
}
test_trap 3
test_trap
##
# Output
#
# ./bash_trap
# Success
# [ERROR] Line: 25 Code: 1 Message: test_trap() requires 1 argument
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment