0

For some monitoring purposes, for a given list of files (that change path daily) I want to launch a tail -f in the background searching for specific strings How do I properly get the exact pid of the tail commands generated by the for loop, so I could kill them later ?

Here's what I'm trying to do which I think gives me the pid of the script and not the tail process.

for f in $(find file...)
do
tail -f $f | while read line
do case $line in
        *string_to_search*) echo " $line" | mutt -s "string detected in file : $1" mail@mail.com;
         ;;
   esac
done &
echo $! >> pids.txt
done
nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • 1
    Looks good though. Please see https://stackoverflow.com/questions/1908610/how-to-get-pid-of-background-process might help maybe – Andre Gelinas Aug 24 '18 at 14:59
  • Not sure if it's good, the when I check the pids I get it's showing "bash", not the "tail -f" spawned which has another pid: `myuser 222617 1 0 17:08 pts/0 00:00:00 -bash` – nullPointer Aug 24 '18 at 15:11
  • Then maybe put that for loop in script1 which would call script2 $f containing your tail/while loop (in background of course). You should then have the PID of each script2 called with a different file with a different PID...just an idea. – Andre Gelinas Aug 24 '18 at 15:49
  • 1
    You are starting a pipeline, and $! returns the pid of the last process in the pipeline, which is the shell executing the while read line loop. FWIW, killing that process should also terminate the tail with a broken pipe signal. Or look at https://stackoverflow.com/questions/3345460/how-to-get-the-pid-of-a-process-in-a-pipeline or https://stackoverflow.com/questions/1652680/how-to-get-the-pid-of-a-process-that-is-piped-to-another-process-in-bash – Jim Janney Aug 26 '18 at 02:36

0 Answers0