gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:12:49 28 4
gpt4 key购买 nike

我正在开发一个脚本来管理一些陷阱。一开始我只用这段代码管理 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 "$1" 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 中的 $1。由于它一次只获取一个陷阱,因此不需要循环。

要设置陷阱,循环遍历您想要的每个陷阱(INT SIGTSTP...)并运行

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 answerstill another .

关于Bash 陷阱,捕获并将它们作为同一函数的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188046/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com