Hacker News new | past | comments | ask | show | jobs | submit login

Most people use Bash trap incorrectly, and it should be documented.

    # All normal and error exits

    trap 'e=$?; trap - EXIT; your cleanup here; exit $e' EXIT

    # Error only trap

    trap 'e=$?; trap - ERR; your error only cleanup here; exit $e' ERR
Save the previous exit condition to preserve it, otherwise it will be destroyed.

Untrapping is necessary to prevent multiple calls, especially if it can call exit or fail within the trap handler.

You don't need an exhaustive list of signals, which is almost never correct in oft touted cargo culted examples.




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: