简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM