Bash – huponexit for non-login shells

bash

This is a followup to Do background processes get a SIGHUP when logging off?.

It seems that huponexit only works for login shells. How do I get that behavior for non-login shells, e.g. the ones that are started in my terminal window?

Sending HUP to the bash from where the processes have been started works as expected, but huponexit doesn't.

Best Answer

You can declare your own code to run when the shell exits.

trap 'kill -HUP $(jobs -lp) 2>/dev/null || true' EXIT

(My earlier proposal of trap 'kill -HUP $$' EXIT doesn't work as of bash 4.2, because if I understand the source correctly bash skips part of its normal cleanup, including HUP resending, when it's already processing an exit condition.)