The solution is to use trap EXIT
, which registers a clean-up action to be run automatically when the function finishes:
function foo {
trap run_cleanup EXIT
if ... ; then
...
return
elif ... ; then
some_command || return 1
else
...
fi
...
}
Note that using trap ... EXIT
in functions is zsh
-specific:
If sig is 0
or EXIT
and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes.
...
If sig is 0
or EXIT
and the trap statement is not executed inside the body of a function, then the command arg is executed when the shell terminates.
In bash
the command is trap ... RETURN
.
If a sigspec is EXIT
(0) the command arg is executed on exit from the shell ... If a sigspec is RETURN
, the command arg is executed each time a shell function or a script executed with the .
or source
builtins finishes executing.