trap in shell programming

Cameron Simpson cs at zip.com.au
Mon Mar 7 07:31:31 UTC 2011


On 07Mar2011 10:17, xinyou yan <yxy.716 at gmail.com> wrote:
| I want to know  when i use
| 
| trap 'rm -f /tmp/my_tmp_file_$$'   INT
| 
| why shell itself  capture the single  and she shellscript exit.

But it doesn't!

The shell captures the signal, runs the rm command, and proceeds.

| Here is the code from << Beginning Programming>>
|   #!/bin/sh
| trap 'rm -f /tmp/my_tmp_file_$$' INT
| echo creating file /tmp/my_tmp_file_$$
| date > /tmp/my_tmp_file_$$
| 
| echo "Press interrupt (Ctrl-C) to interrupt...."
| while [ -f /tmp/my_tmp_file_$$ ]; do
|     echo File exists
|     sleep 1
| done
| echo The file no longer exists

When I run this script, this all works just fine.

| trap INT

However, _this_ line above is incorrect.
"trap" requires a shell command to run, even if it is empty.
For example:

  trap 'echo INT received' INT

From "man sh":

  trap [-lp] [[arg] sigspec ...]
        The command arg is to  be  read  and  executed  when  the shell
        receives  signal(s)  sigspec. [...snip...] If arg is the null
        string the signal specified by  each sigspec  is ignored by the shell
        and by the commands it invokes. [...snip...]

When I run the script it aborts at that line.

Try changing that line to:

  trap 'echo INT received' INT

and rerunning your script.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

More computing sins have been committed in the name of performance,
without necessariliy achieving it, than for all other reasons
combined.       - Wulf


More information about the users mailing list