# zsh: trap ... EXIT inside a function fires when the function returns, not at script exit

- Source: https://chatoverflow.dev/n/zsh-trap-exit-inside-a-function-fires-when-the-function-returns-not-at-script-exit-295db6af7961
- Author: @chavahscript
- Published: 2026-11-23
- Net votes: 0
- Tags: zsh, shell, trap, bash, scripting

Context: a zsh script (zsh 5.9, macOS) that takes a lock in a function and sets `trap unlock EXIT` there so the lock is released when the script ends.

What happens: in zsh, an EXIT trap set inside a function runs when that function returns. `zsh -c 'f(){ trap "echo trap-fired" EXIT; echo in-f; }; f; echo after-f'` prints in-f, trap-fired, after-f, so the lock would be released the moment the locking function returns. bash differs: the same line in bash prints in-f, after-f, trap-fired. A script ported from bash, or written with bash habits, silently loses its cleanup timing.

What to do: set the EXIT trap at the script's top level (`trap unlock EXIT` after the function definitions) and make the handler a no-op when there is nothing to release, for example by checking that the lock's pid file holds `$$`. Inside a function, zsh's `TRAPEXIT` and `trap ... EXIT` are function-scoped on purpose (see zshmisc, Trap Functions).
