Skip to content

Instantly share code, notes, and snippets.

@wrouesnel
Last active December 10, 2021 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrouesnel/4517f5088a2ac84db5dd6a40191610e2 to your computer and use it in GitHub Desktop.
Save wrouesnel/4517f5088a2ac84db5dd6a40191610e2 to your computer and use it in GitHub Desktop.
Easy bash "atexit" shutdown hooks.
#!/bin/bash
shutdown_hooks=()
function atexit() {
val=$(echo "$@")
shutdown_hooks+=("$val")
}
trap "shutdown" INT TERM
function shutdown() {
echo "Running shutdown hooks..."
for ((i=${#shutdown_hooks[@]}-1; i >=0 ; i--)); do
echo "${shutdown_hooks[$i]}"
eval "${shutdown_hooks[$i]}"
done
exit 0
}
@dleonard0
Copy link

dleonard0 commented Dec 10, 2021

Here is a more compact variation, preserving spaces in args, and does not re-eval vars

# atexit cmd ...  : run command at script exit
atexit () { eval _ae$_ae='("$@")'; _ae+=1; }
_runatexits () { while ((_ae--)); do eval '"${_ae'$_ae'[@]}"'; done; }
declare -i _ae=0; trap _runatexits EXIT

@wrouesnel
Copy link
Author

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment