Bash 陷阱、捕获并将它们作为同一函数的参数传递

Bash traps, capture and pass them as arguments on same function

我正在开发一个脚本来管理一些陷阱。一开始我只用这段代码管理 INT 和 SIGTSTP,而且效果很好:

#!/bin/bash
function capture_traps() {
    echo -e "\nDoing something on exit"
    exit 1
}

trap capture_traps INT
trap capture_traps SIGTSTP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0

然后我尝试添加我想要管理的新陷阱,它们是 SIGINT 和 SIGHUP。在第一个实例中,我这样做了(这是有效的):

#!/bin/bash
function capture_traps() {
    echo -e "\nDoing something on exit"
    exit 1
}

trap capture_traps INT
trap capture_traps SIGTSTP
trap capture_traps SIGINT
trap capture_traps SIGHUP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0

然后,我决定根据陷阱在退出时做不同的事情,我不想为每个陷阱创建不同的函数。我知道在 bash 中你可以使用 for item in $@; do 命名法循环函数的参数,所以我试过了,但似乎无法区分陷阱的类型。我制作了这段不起作用的代码。

#!/bin/bash
function capture_traps() {

    for item in $@; do
        case ${item} in
            INT|SIGTSTP)
                echo -e "\nDoing something on exit"
            ;;
            SIGINT|SIGHUP)
                echo -e "\nDoing another thing even more awesome"
            ;;
        esac
    done
    exit 1
}

trap capture_traps INT SIGTSTP SIGINT SIGHUP
read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0

有什么帮助吗?必须有一种方法可以改进我的代码,只对所有陷阱使用一个函数,但我不知道如何...

您可以将参数传递给陷阱处理程序:

#!/bin/bash
function capture_traps() {

    #for item in $@; do
    case "" in
        INT|SIGTSTP)
            echo -e "\nDoing something on exit"
        ;;
        SIGINT|SIGHUP)
            echo -e "\nDoing another thing even more awesome"
        ;;
    esac
    #done
    exit 1
}

for f in INT SIGTSTP SIGINT SIGHUP ; do
    trap "capture_traps $f" "$f"
done

read -p "Script do its stuff here and we use read for the example we pause for time to generate trap event"
exit 0

在上面的代码中(在cygwin,bash 4.3.46上测试过),capture_traps接受一个参数:陷阱的名称。即capture_traps中的</code>。因为它一次只得到一个陷阱,所以它不需要循环。</p> <p>要设置陷阱,循环遍历您想要的每个陷阱 (<code>INT SIGTSTP...) 和 运行s

trap "capture_traps $f" "$f"

第一个参数可以比函数名更通用:它是

shell code ... to be read and executed whenever the shell receives a signal or another event

根据 wiki。因此,命令 capture_traps $f(其中替换了陷阱名称)将 运行 该特定陷阱(第二个参数,"$f"。Et voila!

... 刚刚意识到我应该先检查重复项:)。 Here's another answer and still another.