> This is known as idempotency.<p>No? Idempotency is ensuring that calling the same function with the same input N times will have the exact same effect as calling it once. Adding this defer does _not_ guarantee idempotency, because it has no impact on the body of the script. You can provide just as much idempotency by running `rm -rf /tmp/$script_dir*` on the first line.
While this is great, this only cleans up temporary files on a clean exit (well, depending on the shell), and no trap can catch SIGKILL. I much prefer cleaning up my files _before_ I use them, like:<p>```<p>touch 'temp.txt'<p>exec 3 < 'temp.txt'<p>exec 4 > 'temp.txt'<p>rm -f 'temp.txt'<p>```<p>Now I have file descriptors 3 and 4 available for reading and writing, respectively, and even if I pulled the plug out from my desktop the file will not be anywhere on my filesystem.
Heh! Not sure if it's a cosmic coincidence, but I posted something (<a href="https://news.ycombinator.com/item?id=36410781">https://news.ycombinator.com/item?id=36410781</a>) similar based on <a href="https://github.com/bashup/events">https://github.com/bashup/events</a> a few hours ago in another thread.<p>The version here's much simpler, which has its merit if you need the performance or have a simple (append-only, exit-only) use-case.<p>bashup.events supports removing handlers, one-time events, pseudo-promises, and more. It's easy to use it for something like this, but also modular deferred init/load and more.<p>(linked comment has a little more detail on how I use it.)
I wrote something similar some years ago:
<a href="https://codereview.stackexchange.com/questions/67417/an-atexit-for-bash" rel="nofollow noreferrer">https://codereview.stackexchange.com/questions/67417/an-atex...</a><p>I do not like the way you build expressions by concatenating strings. This is the driving force behind SQL injections.
I'm adding this to my dotfiles because it just seems so dang useful, but this really seems to be the intersection of elegance and hackery that's the epitome of shell scripting. A close second would be that "fork bomb" that's just a bunch of :{}|{} or something weird like that, but `defer` here is actually useful!
This seems conceptually similar to python's `with` statement.<p><a href="https://docs.python.org/3/reference/compound_stmts.html#the-with-statement" rel="nofollow noreferrer">https://docs.python.org/3/reference/compound_stmts.html#the-...</a>
I’m trying to figure out a way this can backfire horribly but falling short of it. Curious to test the interaction with set -e if your defer command also errors. Very clever.