Created
November 22, 2013 16:59
-
-
Save antevens/7603244 to your computer and use it in GitHub Desktop.
Bash signal handler
This file contains 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
# Traps for cleaning up on exit | |
# Originally from http://www.linuxjournal.com/content/use-bash-trap-statement-cleanup-temporary-files | |
declare -a on_sig_items | |
function on_exit() | |
{ | |
echo "Received SIGEXIT, Cleaning up: $i" | |
for i in "${on_sig_items[@]}"; do | |
echo "Executing cleanup statement: $i" | |
eval $i | |
done | |
} | |
function on_break() | |
{ | |
color_echo red "Signal receied, unexpected exit" | |
for i in "${on_sig_items[@]}"; do | |
echo "Executing cleanup statement: $i" | |
eval $i | |
done | |
} | |
function add_on_sig() | |
{ | |
local n=${#on_sig_items[*]} | |
on_sig_items[$n]="$*" | |
if [[ $n -eq 0 ]]; then | |
echo "Setting up signal trap" | |
trap on_exit EXIT | |
trap on_break INT QUIT TERM | |
fi | |
} | |
# Exit on failure function | |
function exit_on_fail { | |
echo "Last command did not execute successfully but is required!" >&2 | |
echo "Exiting and rolling back all changes!" >&2 | |
exit 1 | |
} | |
# USAGE EXAMPLE | |
tmp_dir="$(mktemp -d" | |
chmod -R 700 ${tmp_dir} && add_on_sig "rm -Rf ${tmp_dir}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment