Last active
April 6, 2022 02:53
-
-
Save boltronics/c532eaef6b1776341911 to your computer and use it in GitHub Desktop.
manage_bash_traps.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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