Is it necessary to specify traps other than EXIT?

前端 未结 3 1377
栀梦
栀梦 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 07:41

    To make sure the EXIT signal handler will not be executed twice (which is almost always not what you want) it should always set to be ignored or reset within the definition of the EXIT signal handler itself.

    The same goes for signals that have more than one signal handler defined for them in a program.

    # reset
    trap 'excode=$?; cmd; trap - EXIT; echo $excode' EXIT HUP INT QUIT PIPE TERM
    
    # ignore
    trap 'excode=$?; trap "" EXIT; cmd; echo $excode' EXIT HUP INT QUIT PIPE TERM
    

提交回复
热议问题