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.

# define functions to handle signals
# treat them as errors with appropriate messages
sighup()   {  print_error_and_exit "trap()" "Caught SIGHUP (1). Terminating. Bye!";    }
sigint()   {  print_error_and_exit "trap()" "Caught SIGINT (2). Terminating. Bye!";    }
sigquit()  {  print_error_and_exit "trap()" "Caught SIGQUIT (3). Terminating. Bye!";   }
sigabrt()  {  print_error_and_exit "trap()" "Caught SIGABRT (6). Terminating. Bye!";   }
sigterm()  {  print_error_and_exit "trap()" "Caught SIGTERM (15). Terminating. Bye!";  }

# use the above functions as signal handlers;
# note that the SIG* constants are undefined in POSIX,
# and numbers are to be used for the signals instead
trap 'sighup' 1; trap 'sigint' 2; trap 'sigquit' 3; trap 'sigabrt' 6; trap 'sigterm' 15

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:

trap '' TSTP

# or possibly equivalently
trap '' 18
trap '' 20
trap '' 24

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:

    Trapping signals by number is not well defined. Prefer signal names. [SC2172]
    

    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:

    # shellcheck disable=SC2172
    

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

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