tail and grep log and mail (linux)

askaquestion picture askaquestion · Jan 11, 2011 · Viewed 20.6k times · Source

i want to tail log file with grep and sent it via mail like:

tail -f /var/log/foo.log | grep error | mail -s subject [email protected]

how can i do this?

Answer

Marcus Borkenhagen picture Marcus Borkenhagen · Jan 11, 2011

You want to send an email when emailing errors occur? That might fail ;)

You can however try something like this:

tail -f $log |
grep --line-buffered error |
while read line
do
    echo "$line" | mail -s subject "$email"
done

Which for every line in the grep output sends an email.

Run above shell script with

nohup ./monitor.sh &

so it will keep running in the background.