Trap ERR vs trap EXIT

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2023-03-28

What's the difference between trap ERR:

trap 'cleanup' ERR

mkdir workingdir
# do stuff inside workingdir
# ...

cleanup() {
  rm -rf workingdir

and trap EXIT

trap 'cleanup' EXIT

# ... as before

Answer: EXIT is called, no matter what, when the script is finished, whereas ERR is only called if there are an error. Therefore EXIT is useful for general cleanup.