Shell – does SIGTERM work to terminate bash but not ash or dash

ashdashlinuxshellsignals

Comparing bash, ash and dash, only bash can be terminated by SIGTERM

kill -TERM <pid>

For ash and bash, I need SIGHUP or SIGKILL

kill -HUP <pid>
kill -KILL <pid>

What's the reasoning behind this? Furthermore, the behavior seems to be system-dependent:

  • bash is terminated by SIGTERM on Ubuntu 14.04 Trusty, Ubuntu 16.04 Xenial, Ubuntu 18.04 Bionic, Ubuntu 19.10 Eoan, Ubuntu 20.04 Focal, Debian 8 Jessie, Debian 9 Stretch, Debian 10 Buster, CentOS 8
  • bash is not terminated by SIGTERM on CentOS 6, CentOS 7

Best Answer

This only happens when bash is using the readline line editing library, and only when bash is waiting for input from the user.

A bash --noediting will not be killed by SIGTERM, nor will bash kill itself if running kill -TERM $$.

This happens because the readline() function used by bash to get input from the user, will install its own signal handler for SIGTERM, and restore the original signal disposition before returning. If a SIGTERM happens while readline is waiting for input from the user, readline() will return NULL.

The bash function which calls readline() (yy_readline_get()) will interpret a NULL return as EOF, causing the shell to exit. The scenario is quite similar to that from this answer.

This means that an interactive bash could be also made to survive a SIGTERM by setting IGNOREEOF ;-):

$ bash
$ IGNOREEOF=10
$ echo $$
11096
<kill -TERM 11096 from another terminal>
$ Use "exit" to leave the shell.
<kill -TERM 11096 from another terminal>
$ Use "exit" to leave the shell.
...
<the 10th will get it>
$ exit
$