HACKER Q&A
📣 httbs

How to trap SIGTSTP (ctrl-z) in a Bash script?


Time and time again I've heard things like "Linux is not hard, there's a full army of people online waiting to help you when you run into trouble."

Well, here I am, deep in the Linux trenches, fighting something for which there's little documentation. You are my last hope:

I have the following script:

```bash

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..." shows 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.

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

Thanks!


  👤 tmcb Accepted Answer ✓
You are probably looking for help at the wrong website---anyway, just let me know if that helps.

    suspense_cleanup () {
     echo "Suspense clean up..."
     exit 0
    }

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