4

いくつかのトラップを管理するスクリプトを開発しています。最初は、このコードで 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

何か助けはありますか?すべてのトラップに対して 1 つの関数のみを使用してコードを改善する方法があるはずですが、方法がわかりません...

4

1 に答える 1