Consider multiple subshells, each writing its own log file. Consider that one subshell failed, leading to sending (using some mechanism) of SIGTERM to all the subshells. Upon reception of SIGTERM all the subshells are terminated. However, the SIGTERM-terminated subshell log files are kept. This is the problem.

Question: how to remove subshell log file after reception of SIGTERM?

I tried this:

  rm -f $log_file

trap _term SIGTERM

However, as I understand, this does not work because "Trap handlers are never inherited by subshells".

In the description of trap I see:

When a subshell is entered, traps that are not being ignored are set to the default actions. This does not imply that the trap command cannot be used within the subshell to set new traps.

The last sentence is a bit confusing. Can someone explain is it possible at all to trap SIGTERM (or other) in a subshell?

1 Answer 1


Yes, they are not inherited. But you can define a new trap in the subshell. And the parent shell has its own set of traps.

So then you send a signal to that parent shell, it can catch it and issue its own set of signals to subshells.

Here is a bunch of examples with explanations: https://tldp.org/LDP/abs/html/debugging.html#EX76

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .