Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I kill piped background processes?

Tags:

linux

bash

pipe

Example session:

- cat myscript.sh 
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
# here is were I want tail and grep to die
echo "more code here"

- ./myscript.sh

- ps
  PID TTY          TIME CMD
15707 pts/8    00:00:00 bash
20700 pts/8    00:00:00 tail
20701 pts/8    00:00:00 grep
21307 pts/8    00:00:00 ps

As you can see, tail and grep are still running.


Something like the following would be great

#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"

But that only kills grep, not tail.

like image 903
mcjohnalds45 Avatar asked Nov 22 '25 11:11

mcjohnalds45


1 Answers

Although the entire pipeline is executed in the background, only the PID of the grep process is stored in $!. You want to tell kill to kill the entire job instead. You can use %1, which will kill the first job started by the current shell.

#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"

Even if you just kill the grep process, the tail process should exit the next time it tries to write to standard output, since that file handle was closed when grep exits. Depending on how often example.log is updated, that could be almost immediately, or it could take a while.

like image 72
chepner Avatar answered Nov 24 '25 02:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!