[Linux-disciples] Ctrl+C and scripts

Stephen R Laniel steve at laniels.org
Mon Jan 30 11:25:05 EST 2006


On Fri, Jan 06, 2006 at 10:56:35AM -0500, Stephen R Laniel wrote:
> If you send Ctrl+C (SIGINT, I guess more specifically) to a
> script, it seems as though Ctrl+C only stops the running
> process. So if, for instance, your script is
> 
> #!/bin/sh
> sudo apt-get update
> sudo apt-get upgrade
> 
> and you press Ctrl+C while the update is running, the script
> will continue on to the upgrade and you'll need to press
> Ctrl+C again.
> 
> If you want the SIGINT to interrupt the whole script, how
> would you do that?

I think I found my answer; see 'help trap':

trap: trap [-lp] [arg signal_spec ...]
     The command ARG is to be read and executed when the shell receives
    signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
    is supplied) or `-', each specified signal is reset to its original
    value.  If ARG is the null string each SIGNAL_SPEC is ignored by the
    shell and by the commands it invokes.  If a SIGNAL_SPEC is EXIT (0)
    the command ARG is executed on exit from the shell.  If a SIGNAL_SPEC
    is DEBUG, ARG is executed after every simple command.  If the`-p' option
    is supplied then the trap commands associated with each SIGNAL_SPEC are
    displayed.  If no arguments are supplied or if only `-p' is given, trap
    prints the list of commands associated with each signal.  Each SIGNAL_SPEC
    is either a signal name in <signal.h> or a signal number.  Signal names
    are case insensitive and the SIG prefix is optional.  `trap -l' prints
    a list of signal names and their corresponding numbers.  Note that a
    signal can be sent to the shell with "kill -signal $$".

So then the thing to do in the above example,
it seems to me, is

	#!/bin/sh
	trap "kill $$" SIGINT
	sudo apt-get update
	sudo apt-get upgrade
	trap - SIGINT

This says to kill the pid of the shell that the first line
invoked, if the user sends SIGINT to the script.

-- 
Stephen R. Laniel
steve at laniels.org
Cell: +(617) 308-5571
http://laniels.org/
PGP key: http://laniels.org/slaniel.key
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://lists.bostoncoop.net/pipermail/linux-disciples/attachments/20060130/278c02b9/attachment.pgp


More information about the Linux-disciples mailing list