prajwal
prajwal

Reputation: 69

Trap in linux script not capturing exit code

    testttt(){
    echo after trapp
    }
    test(){
    echo inside testcode
    exit 2
    }
    trap 'testttt' 2
    test

When i run the script i get output ->inside testcode But I was expecting ->inside testcode after trapp Why isnt trap 'testttt' 2 capturing testttt()

Upvotes: 1

Views: 80

Answers (2)

jijinp
jijinp

Reputation: 2662

Add to @chepner answer you can send interrupt to your running script this way:

   testttt(){
    echo after trapp
    }
    test(){
    echo inside testcode
    kill -s SIGINT $$
    }
    trap 'testttt' 2
    test

Where $$ will have PID of your script.

Upvotes: 0

chepner
chepner

Reputation: 531155

Your trap only executes if your script receives SIGINT (signal 2), not any time it exits with status 2.

Instead, you should trap EXIT, then test the exit status inside your handler.

testttt(){
    exit_status=$?
    if [[ $exit_status -eq 2 ]]; then
        echo after trapp
    fi
}
test(){
    echo inside testcode
    exit 2
}
trap 'testttt' EXIT
test

Upvotes: 1

Related Questions