Skip to main content
5 of 7
added 4 characters in body

How to cleanup on suspense (ctrl-z) in a Bash script?

I have the following script:

suspense_cleanup () { echo "Suspense clean up..." } int_cleanup () { echo "Int clean up..." exit 0 } trap 'suspense_cleanup' SIGTSTP trap 'int_cleanup' SIGINT sleep 600 

If I run it and press Ctrl-C, Int clean up... show and it exits.

But if I press Ctrl-Z, the ^Z characters are displayed on the screen and then it hangs.

How can I:

  • Run some cleanup code on Ctrl-Z, maybe even echoing something, and
  • proceed with the suspension afterwards?

Randomly reading through the glibc documentation, I found this:

Applications that disable the normal interpretation of the SUSP character should provide some other mechanism for the user to stop the job. When the user invokes this mechanism, the program should send a SIGTSTP signal to the process group of the process, not just to the process itself.

But I'm not sure if that's applicable here, and in any case it doesn't seem to work.

Edit: Changing sleep 600 to for x in {1..100}; do sleep 6; done also doesn't work.

Edit 2: It works when replacing sleep 600 with sleep 600 & wait. I'm not at all sure why or how that works, or what are the limitations of something like this.