How do you guarantee temp file cleanup with `trap`?
BeginnerConceptFunctions, exit codes, strict mode and traps
Answer
tmpdir=$(mktemp -d)
trap 'rm -rf -- "$tmpdir"' EXIT
curl -fsSo "$tmpdir/app.tgz" "$url"
tar -xzf "$tmpdir/app.tgz" -C "$tmpdir"
The EXIT trap runs on normal exit, on exit N, on a set -e failure, and after a trapped INT/TERM causes an exit. Use single quotes so $tmpdir is expanded when the trap fires. Set the trap immediately after creating the resource.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner