treewide: fix bash exit handlers

Transform exit handlers of the form
trap cleanup EXIT [INT] [TERM] [QUIT] [HUP] [ERR]
(where cleanup is idempotent)
to
trap cleanup EXIT

This fixes a common bash antipattern.

Each of the above signals causes the script to exit. For each signal,
bash first handles the signal by running `cleanup` and then runs
`cleanup` again when handling EXIT.
(Exception: `vscode/*` prevents the second run of `cleanup` by removing
the trap in cleanup`).

Simplify the cleanup logic by just trapping exit, which is always run
when the script exits due to any of the above signals.

Note: In case of borgbackup, the exit handler is not idempotent, but just
trapping EXIT guarantees that it's only run once.

+7 -13
+1 -1
maintainers/scripts/rebuild-amount.sh
··· 35 35 cleanup() { 36 36 rm -rf "${toRemove[@]}" 37 37 } 38 - trap cleanup EXIT SIGINT SIGQUIT ERR 38 + trap cleanup EXIT 39 39 40 40 MKTEMP='mktemp --tmpdir nix-rebuild-amount-XXXXXXXX' 41 41
+1 -3
nixos/modules/services/backup/borgbackup.nix
··· 23 23 on_exit() 24 24 { 25 25 exitStatus=$? 26 - # Reset the EXIT handler, or else we're called again on 'exit' below 27 - trap - EXIT 28 26 ${cfg.postHook} 29 27 exit $exitStatus 30 28 } 31 - trap 'on_exit' INT TERM QUIT EXIT 29 + trap on_exit EXIT 32 30 33 31 archiveName="${if cfg.archiveBaseName == null then "" else cfg.archiveBaseName + "-"}$(date ${cfg.dateFormat})" 34 32 archiveSuffix="${optionalString cfg.appendFailedSuffix ".failed"}"
+1 -1
nixos/modules/services/web-apps/keycloak.nix
··· 569 569 shopt -s inherit_errexit 570 570 571 571 create_role="$(mktemp)" 572 - trap 'rm -f "$create_role"' ERR EXIT 572 + trap 'rm -f "$create_role"' EXIT 573 573 574 574 db_password="$(<"$CREDENTIALS_DIRECTORY/db_password")" 575 575 echo "CREATE ROLE keycloak WITH LOGIN PASSWORD '$db_password' CREATEDB" > "$create_role"
+1 -2
pkgs/applications/editors/vscode/extensions/_maintainers/update-bin-srcs-lib.sh
··· 39 39 function rm_tmpdir() { 40 40 1>&2 printf "rm -rf %q\n" "$tmpDir" 41 41 rm -rf "$tmpDir" 42 - trap - INT TERM HUP EXIT 43 42 } 44 43 function make_trapped_tmpdir() { 45 44 tmpDir=$(mktemp -d) 46 - trap rm_tmpdir INT TERM HUP EXIT 45 + trap rm_tmpdir EXIT 47 46 } 48 47 49 48 1>&2 echo
+1 -2
pkgs/applications/editors/vscode/extensions/cpptools/update_helper.sh
··· 45 45 46 46 function rm_tmpdir() { 47 47 rm -rf "$tmpDir" 48 - trap - INT TERM HUP EXIT 49 48 } 50 49 function make_trapped_tmpdir() { 51 50 tmpDir=$(mktemp -d) 52 - trap rm_tmpdir INT TERM HUP EXIT 51 + trap rm_tmpdir EXIT 53 52 } 54 53 55 54 echo
+2 -4
pkgs/build-support/fetchcvs/nix-prefetch-cvs
··· 21 21 22 22 mkTempDir() { 23 23 tmpPath="$(mktemp -d "${TMPDIR:-/tmp}/nix-prefetch-cvs-XXXXXXXX")" 24 - trap removeTempDir EXIT SIGINT SIGQUIT 24 + trap removeTempDir EXIT 25 25 } 26 26 27 27 removeTempDir() { 28 - if test -n "$tmpPath"; then 29 - rm -rf "$tmpPath" || true 30 - fi 28 + rm -rf "$tmpPath" 31 29 } 32 30 33 31