1
    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()

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

and if instead of EXIT if I put 0 is it the same thing?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.