Examples of interrupt handling

To use single quotes to inhibit command substitution:

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

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:

   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:

   # read and process commands
   for i in *
     if test -d $dir/$i
       cd $dir/$i
       while echo ''$i:''
       trap exit 2   # trap ^C
       read x
         trap ' ' 2      # ignore interrupts
         eval $x

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] [Search] [Index] This site maintained by support@eskimo.com