Skip to content

Instantly share code, notes, and snippets.

@jghiloni
Created October 19, 2018 18:14
Show Gist options
  • Save jghiloni/014e293e6c612a288dc61f6e8cf4f24d to your computer and use it in GitHub Desktop.
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
#!/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