Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps