help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] trap when expected return value may be non-zero?


From: Greg Wooledge
Subject: Re: [Help-bash] trap when expected return value may be non-zero?
Date: Thu, 2 May 2013 16:24:28 -0400
User-agent: Mutt/1.4.2.3i

On Thu, May 02, 2013 at 08:05:54PM +0000, adrelanos wrote:
> HUP (Hang up detected on controlling terminal or death of controlling
> process) should be definitively added.
> 
> INT (Issued if the user sends an interrupt signal (Ctrl + C).) is in,
> because users of my build scripts are free to press Ctrl + C to
> interrupt them for whatever reason. What it does is informing about the
> last $BASH_COMMAND, cleaning up, dismounting an image (because not doing
> so and re-running the build script while the image is still mounted
> could lead to strange errors).
> 
> TERM (Software termination signal (sent by kill by default).) If one
> thinks "build script takes to long, I forgot to add some files" and uses
> kill to stop it, it's best to do the same cleanup as for INT.

It's not typically useful to look at all of these individual signals,
or to trap them all explicitly.  More on this below.

> ERR (Non-expected non-zero return code in rare cases (bugs).) Same
> information and cleanup as if INT or TERM.

This is not a signal, and like Bob suggested, it should not be treated
in the same way that other signals are being treated.

> SIGQUIT (Issued if the user sends a quit signal (Ctrl + D).) ...

The terminal quit signal is typically bound to Ctrl-\, not Ctrl-D.
This can be changed with stty(1) or the equivalent, but mapping
Ctrl-D to QUIT would be pretty bizarre.

Generally, the most common case is that you set up a trap in order to
clean up temporary files or other external resources when you are
killed unexpectedly.  For this case, it's far better to set an EXIT
trap:

trap cleanup EXIT
trap printerrors ERR
cleanup() {
   rm -f "$mytempfile"
   ...
}
printerrors() {
   ...
}

Setting a trap on EXIT is both easier *and* more correct for the common
"clean up" case.  You don't have to enumerate all the signals; it acts
on any signal.  You don't have to worry about figuring out which signal
you received, and then killing yourself with that signal.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]