是否可以在 bash 中检测 *which* 陷阱信号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2175647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:37:35  来源:igfitidea点击:

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

bashbash-trap

提问by Wolf

Possible Duplicate:
Identifying received signal name in bash shell script

可能的重复:
在 bash shell 脚本中识别接收到的信号名称

When using something like trap func_trap INT TERM EXITwith:

当使用类似的东西trap func_trap INT TERM EXIT时:

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

Is there a way in the function block to detect whichtrap 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?

或者我是否需要为每个陷阱类型编写一个单独的函数来做不同的事情?是否有保存最新接收信号的 bash 变量?

Thanks in advance!

提前致谢!

采纳答案by nos

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.

没有任何参数或保存被捕获信号的变量的文档提示,因此您必须为每个要表现不同的陷阱编写函数/陷阱语句。

回答by camh

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

您可以实现自己的陷阱函数,自动将信号传递给函数:

trap_with_arg() {
    func="" ; 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.

func_trap 的第一个参数是信号的名称。