How do you make a function's cleanup run even if a command in the middle fails?
AdvancedConceptFunctions, exit codes, strict mode and traps
Answer
Run the body in a subshell with its own EXIT trap, so cleanup is scoped to the function:
with_maintenance() ( # note: ( ) body = subshell
set -e
enable_maintenance_page
trap disable_maintenance_page EXIT
"$@"
)
with_maintenance run_migrations || die "migration failed, maintenance page removed"
The trap fires when the subshell exits for any reason. The cost: variable changes inside the function do not reach the caller.
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