2

I need to disable some(not all) of the traps temporarily in my function and then re-activate them. But I get an unexpected behaviour(I'm pretty new to traps and signals though) when I'm doing it:

function hello(){    
    cleanup(){
        echo bye!!
    }
    trap cleanup RETURN EXIT INT

    echo "hello!!"

    echo "echo hello2!!" > file2

    trap '' RETURN EXIT
    source file2
    sleep 10
    trap cleanup RETURN EXIT <-- last line
}

what I expect is seeing this:

hello!!
hello2!!
bye!!

and ok that's what I get. But now when commenting out the last line(specified in the snippet) I still expect the same output, because I've not disabled the trap for the INT signal and I don't need to re-enable it, but then I'm getting this:

hello!!
hello2!!
^C

which means the trap for INT has been disabled too. Is trap '' RETURN EXIT doing something more than ignoring those two signals? I'm afraid the first case is also working as expected by chance and I'm having a wrong understanding of the whole thing.

I'm using GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu).

  • Your shell will run sleep as an external command, as a child process in a foreground job and consequently, while sleep is running it will be the recipient of any ^C -> SIGINT signal, not the shell. Trap handlers cannot be inherited by child processes, only the ignore/default signal dispositions can. – mosvy Aug 3 '19 at 6:19
  • @mosvy but in the first case (last line "not commented") I also send ^C and it works... Wouldn't that then contradict to what you've said here? thanks. – aderchox Aug 3 '19 at 6:24
  • What "works"? Please set separate traps for each trap 'echo INT' INT, etc. Only the RETURN trap is triggered in the 1st case, which you have disabled in the 2nd case. – mosvy Aug 3 '19 at 6:32
  • By "works" I mean even with the "sleep" being present and the last line uncommented, after the "^C", the "bye!!" IS printed. So opposite to what I understand from your point(while sleep is running it will be the recipient of any ^C -> SIGINT signal, not the shell. Trap handlers cannot be inherited by child processes) the trap IS being inherited by the sleep. Maybe I'm wrong I'd be grateful if this is the answer you post it as an answer and explain it more. Thanks. – aderchox Aug 3 '19 at 12:35
  • 2
    In the 1st case, the bye!! will be printed by the RETURN trap script (upon exiting your hello() function, after the sleep was interrupted by ^C), not by the the INT trap script. – mosvy Aug 3 '19 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.