2

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.

mcjohnalds45
  • 667
  • 1
  • 8
  • 16

2 Answers2

5

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

you could add kill %1 at the end of your script.

That will kill the first background created, that way no need to find out pids etc.

fduff
  • 3,671
  • 2
  • 30
  • 39
  • 2
    `kill %1` will kill the *first* job created, not the last one (although in the example, there is only one background job, so first and last are the same). `kill %%` or `kill %` would kill the current (i.e., most recently created) job. – chepner Nov 11 '13 at 13:14
  • 3
    This clearly does work, but does anyone know where it is officially document? I was hoping to read more about this, but there's nothing in `man kill` or anywhere else that I have found so far via Web search. – Steve Jorgensen Mar 07 '19 at 18:42
  • 1
    @SteveJorgensen Go [here](https://stackoverflow.com/a/55422125/9608759) or if that link does not work in the future, the documentation is in bash manual. `man bash` and search for `/jobspec`. – Asocia Jan 16 '23 at 14:19