UNIX Guide, for beginners and Mac OS X users
You are here: SillyDog701 > UNIX Guide >SillyDog701 > UNIX Guide > (index) supportSupport - ask in our friendly forums.

Examples of interrupt handling

To use single quotes to inhibit command substitution:

   #!/bin/sh
   trap 'echo `pwd` >>$HOME/errdir' 2 3 15
   for i in /bin /usr/bin /usr/any/bin
   do
   cd $i
   some series of commands in the directory $i
   done

The file errdir will contain the name of the directory being worked on when the procedure is interrupted. What happens if the same procedure has double quotes around it?

   trap "echo `pwd` >errdir" 2 3 15 

The file errdir will just contain the name of the directory from which the procedure was invoked because the pwd command would be substituted on the first scan by the shell and not when it is invoked in the script.

To remove temporary files when a procedure is interrupted:

   #!/bin/sh
   temp=/tmp/file.$$
   trap 'rm $temp; exit' 0 1 2 3 15
   ls > $temp
   .....  

If any of the named signals are encountered, the command rm $temp; exit will be executed. The exit command is needed to terminate the execution of the whole procedure.

To continue processing commands after a trap command:

   #!/bin/sh
   # read and process commands
   dir=`pwd`
   for i in *
   do
     if test -d $dir/$i
     then
       cd $dir/$i
       while echo ''$i:''
       trap exit 2   # trap ^C
       read x
       do
         trap ' ' 2      # ignore interrupts
         eval $x
       done
     fi
   done

The shell continues to process commands after a trap command. The entire procedure is terminated if interrupted when waiting for input, but the interrupt is ignored while executing a command. The command list is an explicitly quoted null command and so the signal is ignored by the shell.


[Home]UNIX Guide home | [Search]search | index
Page URL: http://sillydog.org/unix/
[SillyDog701] [Netscape] [MozInfo701] [MacCentre701] [UNIX Guide] [AntTunes701][Forums] [Search] [Change Log] [Feedback] [About Us] [Sitemap]
This UNIX Guide maintained by SillyDog701, portion of this Guide is based on UNIXhelp. UNIXhelp is copyright University of Edinburgh. This page was last modified on 14 March, 2006
Netscape NOW!Made on a Mac
support MozInfo701 and SillyDog701