Skip to content

Instantly share code, notes, and snippets.

@mattolenik
Created September 12, 2018 16:03
Show Gist options
  • Save mattolenik/bb2e206a36a4f98121695c25e53a1e7e to your computer and use it in GitHub Desktop.
Save mattolenik/bb2e206a36a4f98121695c25e53a1e7e to your computer and use it in GitHub Desktop.
bash trap add
# From https://stackoverflow.com/questions/3338030/multiple-bash-traps-for-the-same-signal
# note: printf is used instead of echo to avoid backslash
# processing and to properly handle values that begin with a '-'.
log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$@"; exit 1; }
# appends a command to a trap
#
# - 1st arg: code to add
# - remaining args: names of traps to modify
#
trap_add() {
trap_add_cmd=$1; shift || fatal "${FUNCNAME} usage error"
for trap_add_name in "$@"; do
trap -- "$(
# helper fn to get existing trap command from output
# of trap -p
extract_trap_cmd() { printf '%s\n' "$3"; }
# print existing trap command with newline
eval "extract_trap_cmd $(trap -p "${trap_add_name}")"
# print the new trap command
printf '%s\n' "${trap_add_cmd}"
)" "${trap_add_name}" \
|| fatal "unable to add to trap ${trap_add_name}"
done
}
# set the trace attribute for the above function. this is
# required to modify DEBUG or RETURN traps because functions don't
# inherit them unless the trace attribute is set
declare -f -t trap_add
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment