I would like to trap the exit hook of a function. Bash provides a nice signal called RETURN (non-POSIX) which get called when a function returns, such as
function test_trap() {
trap 'echo trapped' RETURN
sleep 10 # simulate time-consuming commands
echo done
}
I see “trapped” when the function returns, even if I send a SIGINT with Ctrl C. Is there similar functionality for Zsh? I tried EXIT in Zsh, but it only traps normal returns, not when I interrupt with SIGINT. I also tried trapping both EXIT and INT with the same hook function, but it has two issues:
- The hook expression is evaluated twice when I interrupt it. No big deal; my hook expression happens to be idempotent.
- The
EXITin Zsh is local: when returning from the function, the original hook is recovered. This is similar to how a local variable shadows a global one. Unfortunately, theINThook is always global, so any hook I specify will overwrite the global one. I would need to remember the originalINThook, and recover it later. It’s very tricky to do it correctly; I may have a try on this.