Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65846776/how-to-pipe-background-processes-in-a-shell-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...