2016-12-16 36 views
3

我正在开发一个管理一些陷阱的脚本。一开始,我只设法INT和SIGTSTP与此代码和它工作得很好:Bash陷阱,捕获并将它们作为相同函数的参数

#!/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 [email protected]; do命名法的一个函数的参数,所以我尝试了,但它似乎没有工作试图区分这种陷阱。我使这个代码不起作用。

#!/bin/bash 
function capture_traps() { 

    for item in [email protected]; 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 

任何帮助?必须有仅使用一个功能适用于所有的陷阱,以提高我的代码的方式,但我不知道怎么...

回答

2

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

#!/bin/bash 
function capture_traps() { 

    #for item in [email protected]; 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需要一个参数:陷阱的名称。那$1capture_traps。由于它一次只能获得一个陷阱,因此它不需要循环。

要设置陷阱,在你想每个陷阱的循环迭代(INT SIGTSTP ...)并运行

trap "capture_traps $f" "$f" 

的第一个参数可以比函数名更普遍的:它是

壳代码...被读取并每当壳接收信号或另一事件执行

wiki。因此,命令capture_traps $f(与取代的陷阱名称)将在那个特定的陷阱(第二个参数,"$f"。等瞧!

运行...只是意识到我应该检查重复第一:)。 Here's another answerstill another