Is it necessary to specify traps other than EXIT?

前端 未结 3 1380
栀梦
栀梦 2021-02-02 07:28

I see a lot of shell scripts that do:

trap cmd 0 1 2 3 13 15 # EXIT HUP INT QUIT PIPE TERM

In every shell I have access to at the moment, all the traps oth

3条回答
  •  时光取名叫无心
    2021-02-02 08:06

    I think trap 0 is executed just prior to script termination in all cases, so is useful for cleanup functionality (like removing temporary files, etc). The other signals can have specialized error handling but should terminate the script (that is, call exit).

    What you have described, I believe, would actually execute cmd twice. Once for the signal (for example SIGTERM) and once more on exit (trap 0).

    I believe the proper way to do this is like the following (see POSIX specification for trap):

    trap "rm tmpfile" 0
    trap "exit 1" TERM HUP ... 
    

    This ensures a temporary file is removed upon script completion, and lets you set custom exit statuses on signals.

    NOTE: trap 0 is called whether a signal is encountered or not.

    If you are not concerned with setting an exit status, trap 0 would be sufficient.

提交回复
热议问题