Created
October 19, 2018 18:14
-
-
Save jghiloni/014e293e6c612a288dc61f6e8cf4f24d to your computer and use it in GitHub Desktop.
a silly little script to get bash's `trap` function to act a bit like go's `defer` keyword
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
#!/bin/bash | |
function defer() { | |
existing=$(trap -p EXIT | sed -e "s/^trap -- '\(.*\)' EXIT$/\1/" -e "s/\'\\\'\'/'/g") | |
new="$@" | |
if [ ! -z "${existing}" ]; then | |
existing="${existing} ;" | |
fi | |
trapCmd="{ ${new} ; ${existing} }" | |
trap "$trapCmd" EXIT | |
} | |
defer "echo 'bye'" | |
defer "echo 'hi'" | |
echo "this should be first" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment