2016-12-16 4 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" 

는 첫 번째 인수는 함수 이름보다 더 일반적 일 수있다 실행하려면이

입니다

쉘 코드 ... 판독 쉘 신호 또는 다른 이벤트를 수신 할 때마다 실행되는,187,321 당

0. 따라서 capture_traps $f (트랩 이름이 대체 된) 명령은 특정 트랩 (두 번째 인수 인 "$f")에서 실행됩니다. Et voila!

... 중복을 먼저 확인해야 함을 알았습니다 :). Here's another answerstill another.