Trapping on EXIT is a really convenient way of cleaning up after yourself when your script ends.
The nice thing about it is that you don't need to handle all sorts of signals,
handle them, and re-throw them. It makes for a single clean point to define
your exit handlers.
Unfortunately, I've noticed that EXIT handlers don't play so nice in
interactive shells. This is of particular interest when you background a
subshell from them:
{
trap 'rm tempfile' EXIT
dowork tempfile
} &
...
kill $!
This works fine from a script (non-interactive) but not when performed from the
prompt.
Here's some demonstrational code:
interactive:
~ $ { trap 'echo exiting' EXIT; sleep 5; } & sleep 1; kill $!
[1] 59061
[1]+ Terminated: 15 { trap 'echo exiting' EXIT; sleep 5; }
non-interactive:
~ $ bash -c '{ trap "echo exiting" EXIT; sleep 5; }' & sleep 1; kill $!
[1] 59168
exiting
[1]+ Terminated: 15 bash -c '{ trap "echo exiting" EXIT; sleep 5; }'
So, why is this, is this a bug, and we have this fixed? I like being able to
rely on my EXIT handler.
Cheers,
Maarten.
smime.p7s
Description: S/MIME cryptographic signature
