Is it possible to detect *which* trap signal in bash? [duplicate]

孤街浪徒 提交于 2019-12-17 18:48:50

问题


Possible Duplicate:
Identifying received signal name in bash shell script

When using something like trap func_trap INT TERM EXIT with:

func_trap () {
    ...some commands...
}

Is there a way in the function block to detect which trap has called it?

Something like:

func_trap () {
    if signal = INT; then
        # do this
    else
        # do that
    fi
}

Or do I need to write a separate function for each trap type that does something different? Is there a bash variable that holds the latest received signal?

Thanks in advance!


回答1:


No documentation hints of any argument or variable holding the signal that was trapped, so you'll have to write a function/trap statement for each trap you want to behave differently.




回答2:


You can implement your own trap function that automatically passes the signal to the function:

trap_with_arg() {
    func="$1" ; shift
    for sig ; do
        trap "$func $sig" "$sig"
    done
}

$ trap_with_arg func_trap INT TERM EXIT

The first argument to func_trap will be the name of the signal.



来源:https://stackoverflow.com/questions/2175647/is-it-possible-to-detect-which-trap-signal-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!