4

I need to write a zsh function with multiple exit points and execute the same clean-up command at every one of them:

function foo {
    if ... ; then
        ...
        run_cleanup
        return
    elif ... ; then
        some_command || (run_cleanup ; return 1)
    else
        ...
    fi
    ...
    run_cleanup
}

Is there a way to avoid repeating run_cleanup at every exit point (which is very error-prone)?

1 Answer 1

6

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.