Search code examples
linuxbashsubprocesstermination

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


The question applies to a script such as the following:

Script

#!/bin/sh

SRC="/tmp/my-server-logs"

echo "STARTING GREP JOBS..."
for f in `find ${SRC} -name '*log*2011*' | sort --reverse`
do
    (
        OUT=`nice grep -ci -E "${1}" "${f}"`
        if [ "${OUT}" != "0" ]
        then
            printf '%7s : %s\n' "${OUT}" "${f}"
        else
            printf '%7s   %s\n' "(none)" "${f}"
        fi
    ) &
done

echo "WAITING..."
wait

echo "FINISHED!"

Current behavior

Pressing Ctrl+C in console terminates the script but not the already running grep processes.


Solution

  • 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