0

doesn't grab $ERROR and no email or killing the tail. what am i doing wrong?

tail -F --max-unchanged-stats=5 somelogfile.log | grep -B4 "FATAL" | while read ERROR
do
    echo $ERROR | mail -s 'FATAL ERROR' [email protected] && pkill -P $$ tail
done
1

2 Answers 2

0

Add "--line-buffered" to the grep command. But as stated in the answer by @Nick, you will get an email for each line. May want to just remove the "-B4" argument from the grep command.

tail -F --max-unchanged-stats=5 somelogfile.log | grep -B4 --line-buffered "FATAL" | while 
read ERROR
do
    echo "$ERROR" | mail -s 'FATAL ERROR' [email protected]
done

Try this. I tested on my CentOS 6.9 VM and I believe it does what you are looking to accomplish. When the script is first started, you may get a few emails if there are "FATAL" messages near the bottom of the log file.

#!/bin/bash

tail -f --max-unchanged-stats=5 somelogfile.log | grep --line-buffered "FATAL" | while read ERROR
do
    grep -B4 "$ERROR" somelogfile.log \
    | mail -s 'FATAL ERROR' [email protected]
done 
3
  • well i need the last 4 lines to be emailed from grep output would there be another approach to this?
    – Khorem
    Commented Jun 7, 2017 at 17:14
  • @Khorem, try the script I added to my answer. Note that the '-B4 argument is removed from the first grep.
    – Deathgrip
    Commented Jun 7, 2017 at 18:01
  • I was thinking it was something you would want to run in a continuous loop. Glad I can help.
    – Deathgrip
    Commented Jun 7, 2017 at 20:26
0

tail and grep probably buffer stdout, so the while loop does not see it. If you have stdbuf (it should be available on Linux, but I'm not sure about other systems), try

stdbuf -o0 tail -F --max-unchanged-stats=5 somelogfile.log | stdbuf -o0 grep -B4 "FATAL" | while read ERROR ;do ... ;done

But there is another problem: The while read ERROR will read one line and assign it to ERROR each time around the loop. Your grep prints four lines before the FATAL line, so you'd be sending five emails, not one.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .