Archive | March 2011

Handling Shell Script Interrupts


A Real Screen Shot

A Real Screen Shot

If you do much shell scripting, then handling shell interrupts is something you should consider.  As a user is interacting with your script, they may decide to interrupt it by typing Ctrl-C, for example.  Typically this will interrupt your shell script execution, forcing it to exit.

Depending on what your shell script is doing, this could leave behind temporary files, or leave other files in a broken state.  It would be useful if you could trap the interrupt, and handle it safely, before exiting the script.
This can be achieved on most shells using the ‘trap’ command.  The trap command takes the following syntax:

trap [OPTIONS] [[ARG] SIGSPEC ... ]

The ARG is the command to be executed on signal delivery, while SIGSPEC is the name of the signal(s) to trap.  Options include -h for help, -l to list signal names, or -p to print all defined signal handlers.

For example, to always return a ‘user aborted’ error code, the following line in your script could be used.  Whatever value given to $exit_user_abort would be returned.

trap 'echo "`basename $0`: Ouch! User Aborted." 1>&2; exit $exit_user_abort' 1 2 15

The numbers 1, 2 and 15 at the end of this example define which interrupts we’re interested in trapping.  These numbers correspond to different kinds of interrupts.  A short list is given here, but you can use ‘trap -l’ for a complete list.

Signal Number Signal Name Explanation
0 EXIT exit command. Script has executed successfully.
1 HUP Hang Up. The user session has disconnected.
2 INT Interrupt.  Ctrl-C (or other shell interrupt signal) has been given.
3 QUIT Quit.  Ctrl-\ (or other shell quit signal) has been given.
6 ABRT Abort signal.
15 TERM Terminate.  Kill command has been issued against your script.

If your trap runs several commands, it’s possibly neater to call a shell function than list the commands in-line, as above.  For example:

trap funcname 1 2 15

funcname
# Function to handle interrupts
{
echo "`basename $0`: Ouch! User Aborted." 1>&2
exit $exit_user_abort
}
Advertisements
%d bloggers like this: