Skip to content
Advertisement

How to trap CTRL+Z in Linux POSIX shell script; possible or not?

I am a Linux shell scripter, I would like to know if it is possible to trap signal for script sleep:

That is Ctrl+z?

I do it at the moment like this and would like to trap that sleep signal too.

JavaScript

Where the print_error_and_exit function just does as its name says.


Goal: I would like to ignore this signal, if typed on the terminal (obviously this matters).

Advertisement

Answer

To ignore Ctrl+Z typed from a terminal, you can do:

JavaScript

As noted by others, there are other signals that cannot be blocked, such as SIGKILL and SIGSTOP.

Many shells map Ctrl+ to SIGKILL and Ctrl+C to SIGINT.

stty -a should show settings for sending “susp” (SIGTSTP), “intr” (SIGINT) and “quit” (SIGKILL). These keystrokes can be rebound by the user if desired.

Editor’s notes:

  • You cannot use SIGTSTP pseudonym in a POSIX shell script.

  • Even if you know for sure what exact signal number your terminal sends, if writing a script for general use, you ought to block all those three possibilities.

  • ShellCheck warning, and I quote:

    JavaScript

    Means these signal numbers can vary between platforms, try 15 for SIGTERM and you will see no warning at all as that one is POSIX standardized. Ergo, you might want to disable these after you’ve tested your code with:

    JavaScript

    Link to wiki: https://github.com/koalaman/shellcheck/wiki/SC2172

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement