Search code examples
shellpipebackground-process

How to pipe background processes in a shell script


I have a Shell script that starts a few background processes (using &) and are automatically killed when the user calls Ctrl+C (using trap). This works well:

#!/bin/sh

trap "exit" INT TERM ERR
trap "kill 0" EXIT

command1 &
command2 &
command3 &

wait

Now I would like to filter the output of command3 with a grep -v "127.0.0.1" to exclude all the line with 127.0.0.1. Like this:

#!/bin/sh

trap "exit" INT TERM ERR
trap "kill 0" EXIT

command1 &
command2 &
command3 | grep -v "127.0.0.1" & 

wait

The problem is that the signal Ctrl+C doesn't kill command3 anymore.

Is there a way to capture pipe command3 with the grep in order to be able to kill at the end of the process?

Thanks


Solution

  • I will answer my own question. The problem was in the trap too limited. I changed to kill all jobs properly.

    #!/bin/sh
    
    killjobs() {
        for job in $(jobs -p); do
            kill -s SIGTERM $job > /dev/null 2>&1 || (sleep 10 && kill -9 $job > /dev/null 2>&1 &)
        done
    }
    trap killjobs EXIT
    
    command1 &
    command2 &
    command3 | grep -v "127.0.0.1" & 
    
    wait