Bash: How do I make sub-processes of a script be terminated, when the script is terminated? Bash: How do I make sub-processes of a script be terminated, when the script is terminated? bash bash

Bash: How do I make sub-processes of a script be terminated, when the script is terminated?


Write a trap for Ctrl+c and in the trap kill all of the subprocesses. Put this before your wait command.

function handle_sigint(){    for proc in `jobs -p`    do        kill $proc    done}trap handle_sigint SIGINT


A simple alternative is using a cat pipe. The following worked for me:

echo "-" > test.text; for x in 1 2 3; do     ( sleep $x; echo $x | tee --append test.text; ) & done | cat

If I press Ctrl-C before the last number is printed to stdout. It also works if the text-generating command is something that takes a long time such as "find /", i.e. it is not only the connection to stdout through cat that is killed but actually the child process.

For large scripts that make extensive use of subprocesses the easiest way to ensure the indented Ctrl-C behaviour is wrapping the whole script into such a subshell, e.g.

#!/usr/bin/bash(    ...) | cat

I am not sure though if this has the exactly same effect as Andrew's answer (i.e. I'm not sure what signal is sent to the subprocesses). Also I only tested this with cygwin, not with a native Linux shell.