Reputation: 27
I'm currently monitoring a log file and my ultimate goal is to write a script that uses tail -n0 -f
and execute a certain command once grep
finds a correspondence. My current code:
tail -n 0 -f $logfile | grep -q $pattern && echo $warning > $anotherlogfile
This works but only once, since grep -q stops when it finds a match. The script must keep searching and running the command, so I can update a status log and run another script to automatically fix the problem. Can you give me a hint?
Thanks
Upvotes: 0
Views: 81
Reputation: 355
use a while loop
tail -n 0 -f "$logfile" | while read LINE; do
echo "$LINE" | grep -q "$pattern" && echo "$warning" > "$anotherlogfile"
done
Upvotes: 1
Reputation: 14520
awk
will let us continue to process lines and take actions when a pattern is found. Something like:
tail -n0 -f "$logfile" | awk -v pattern="$pattern" '$0 ~ pattern {print "WARN" >> "anotherLogFile"}'
If you need to pass in the warning message and path to anotherLogFile
you can use more -v
flags to awk
. Also, you could have awk
take the action you want instead. It can run commands via the system()
function where you pass the shell command to run
Upvotes: 1