Is sth wrong with the following trap?

trap cleanup SIGINT

cleanup() {
            echo "Exiting script ..."

I never see the echo command when hitting Ctrl+c

The snippet is at the bottom of a larger script having some infinite while loops.

$ bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
  • 1
    I see nothing wrong with this and testing it works as expected. Is the trap actually installed at the time when you press Ctrl+C? – Kusalananda Feb 2 '18 at 10:17
  • For some reason, placing the snippet at the top of the script worked ... so this must be the case, it was not installed – pkaramol Feb 2 '18 at 10:20

The trap has to have been activated/installed at the time when you press Ctrl+C, or it will (obviously) not trigger. The function should also have been defined at that point. This means moving the code up to the top (somewhere in the beginning) of your script.

Additionally, you should probably define the function before installing the trap, or you'll get a "not found" error if the trap is triggered in-between the two.



cleanup() { echo 'Exiting script ...'; }

trap cleanup SIGINT

sleep 300

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.