2016-12-16 31 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