Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: How to trap EXIT like in bash



On Apr 4,  5:20pm, Thorsten Kampe wrote:
}
} In Zsh, `trap "echo trapped" EXIT` triggers only on normal exit, but 
} `trap "echo trapped" EXIT INT` will actually trigger twice on Ctrl-C.

Hmm.  This seems to be a side-effect of the rule that the EXIT trap does
not run from inside other traps.  The default response to INT in a script
is to behave as if 'trap "exit 130" INT' so the EXIT trap is not run.  In
your second (executes twice) example, the script doesn't exit until after
the INT trap has completed.

} How can I trap normal exit, Ctrl-C, SIGTERM and SIGHUP so trap 
} function will only run once?

Just add an explicit "exit" to the trap itself:

    trap "echo trapped; exit" EXIT HUP INT TERM

This also works:

    zshexit() { echo trapped }
    trap exit HUP INT TERM

Curiously in an interactive shell, the following prints "trapped" exactly
one time, even though my first answer above also works interactively:

    trap "echo trapped" EXIT
    trap exit HUP INT TERM

However, that does not work in a script.  I'm not sure why interactive
matters here.



Messages sorted by: Reverse Date, Date, Thread, Author