Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Many examples for trap use trap ... INT TERM EXIT for cleanup tasks. But is it really necessary to list all the three sigspecs?

The manual says:

If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.

which I believe applies whether the script finished normally or it finished because it received SIGINT or SIGTERM. An experiment also confirms my belief:

$ cat ./trap-exit
trap 'echo TRAP' EXIT
sleep 3
$ ./trap-exit & sleep 1; kill -INT %1
[1] 759
[1]+  Interrupt               ./trap-exit
$ ./trap-exit & sleep 1; kill -TERM %1
[1] 773
[1]+  Terminated              ./trap-exit

Then why do so many examples list all of INT TERM EXIT? Or did I miss something and is there any case where a sole EXIT would miss?

share|improve this question
up vote 6 down vote accepted

The POSIX spec doesn't say much about the conditions resulting in executing the EXIT trap, only about what its environment must look like when it is executed.

In Busybox's ash shell, your trap-exit test does not echo 'TRAP' before exiting due to either SIGINT or SIGTERM. I would suspect there are other shells in existance that may not work that way as well.

# /tmp/test.sh & sleep 1; kill -INT %1
[1]+  Interrupt                  /tmp/test.sh
# /tmp/test.sh & sleep 1; kill -TERM %1
[1]+  Terminated                 /tmp/test.sh
share|improve this answer

Yes, there is a difference.

This script will exit when you press Enter, or send it SIGINT or SIGTERM:

trap '' EXIT
echo ' --- press ENTER to close --- '
read response

This script will exit when you press Enter:

echo ' --- press ENTER to close --- '
read response

* Tested in sh, Bash, and Zsh.   (no longer works in sh when you add a command for trap to run)

There's also what @Shawn said: Ash and Dash don't trap signals with EXIT.

So, to handle signals robustly, it's best to avoid trapping EXIT altogether, and use something like this:

cleanup() {
    echo "Cleaning stuff up..."

trap cleanup INT TERM
echo ' --- press ENTER to close --- '
read var
share|improve this answer
The solution with cleanup does the right thing - very elegant! It has become an idiom for my bash scripts with mktemp calls. – Bjoern Dahlgren Jan 6 at 13:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.