0

This question already has an answer here:

#!/bin/bash
sudo tail -fn0 /home/main/time.log |
grep -o --line-buffered 'garage\|garden\|porch' | head -1 |
    while read line; do 
sudo pkill -f porch.sh &
sudo pkill -f garage.sh &
done

I'm trying to write a script that monitors a log, and upon matching a keyword, it will fire off some commands.

Problem is, what I've pieced together will work only once, then exit and stop monitoring.

I have "head -1" added to grep, because I want this to execute after the first keyword only, and prevent it from executing a multitude of times should multiple keywords appear in the tail of the log. So, basically, If multiple keywords appear in the tail, I want it to execute at the first keyword, ignore the rest of the keywords, execute the scripts listed, then go back to monitoring the tail of the log.

I would prefer the script to remain active after it matches a keyword and continue monitoring the tail of the log for any new keywords that might get logged.

Any advice is much appreciated. Thank you!

marked as duplicate by roaima, Jeff Schaller, Isaac, msp9011, Kiwy Aug 29 '18 at 9:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • do you want to run the script continuously(every second)? – msp9011 Aug 28 '18 at 8:58
  • 1
    "will work only once, then exit" ... well, what did you expect with head -1 in there? – muru Aug 28 '18 at 9:25
  • The reason I added head -1, I didn't want the script to execute more than once if multiple keywords appeared in the log. If I remove "head -1", and multiple keywords appear in the tail of the log, it will execute the scripts for each and every keyword that appears. – fizers Aug 28 '18 at 10:23
  • Either you want it to run once, or you want it to run multiple times. Pick one. – wurtel Aug 28 '18 at 12:55
0

I would recommend you to use infinite loop if you want it to keep monitoring and just add and sleep inside your shell to tell them how many time need to pass to monitor again, if you're using bash shell that would be something like this:

#!/bin/bash
while true
do
   sudo tail -fn0 /home/main/time.log |
   grep -o --line-buffered 'garage\|garden\|porch' | head -1 |
   while read line; do 
      sudo pkill -f porch.sh &
      sudo pkill -f garage.sh &
   done
   sleep 1 #change it for the time you want it to keep it monitoring again
done

Not the answer you're looking for? Browse other questions tagged or ask your own question.