Skip to content

Instantly share code, notes, and snippets.

@boltronics
Last active April 6, 2022 02:53
Show Gist options
  • Select an option

  • Save boltronics/c532eaef6b1776341911 to your computer and use it in GitHub Desktop.

Select an option

Save boltronics/c532eaef6b1776341911 to your computer and use it in GitHub Desktop.
manage_bash_traps.sh
#!/bin/bash
# Get the commands associated with a specific signal.
function get_current_trap()
{
local -r trap="${1-EXIT}"
# It does not seem possible to print commands set for ERR
if [ "${trap}" != "ERR" ]
then
trap -p ${trap} | sed "s/trap -- '\(.*\)' ${trap}.*/\1/"
fi
}
# Add a command to one or more signals.
function add_to_trap()
{
local -r add_command="${1}"
shift
local -r traps="${@-EXIT}"
for trap in ${traps}
do
trap "$(get_current_trap ${trap})${add_command};" ${trap}
done
}
# Remove commands from one or more signals.
function rm_from_trap()
{
local -r remove_command="${1}"
shift
local -r traps="${@-EXIT}"
for trap in ${traps}
do
trap "$(trap -p ${trap} | sed \
"s/trap -- '\(.*\)' ${trap}/\1/;s/${remove_command};//")" ${trap}
done
}
declare -r managed_traps='SIGQUIT EXIT ERR'
add_to_trap 'echo trap is printing' SIGQUIT EXIT
add_to_trap 'echo trap is still printing' SIGQUIT EXIT
add_to_trap 'echo trap is taking forever' SIGQUIT EXIT
rm_from_trap 'echo trap is printing' SIGQUIT EXIT
rm_from_trap 'echo trap is taking forever' SIGQUIT
trap -p
echo "Executing the last line of '${0}'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment