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] [Search] [Index] This site maintained by bondaren@thsun1.jinr.ru