Linux – Send email based on grep results

command-line-interfacegreplinuxperlterminal

I'm using WebInject (CLI not GUI) to test out online web services. I was going to go with a third party until I found this little gem and realized what I could save…

What I want to accomplish is to grep the results of WebInject (Perl script) . If it finds a pattern then pipe the results to mail. I'm new at this and am not quite sure how to write the logic for evaluating the results and sending it to mail.

This is what I have so far:

$ perl webinject.pl | grep 'TEST CASE FAILED'

I only want to send an email if grep finds a match, otherwise no email should be sent. I'd like to set this up with cron to run at 10 or 15 minute intervals.

As a side note, is grep able to grab leading and trailing characters from a matching pattern?

UPDATE 1: figured out leading and trailing lines (-A # -B #)

Thanks very much!

Best Answer

Take a look to this answer echo based on grep result
It's almost the same, take the answer that better fit your need then suppress the echo No part and remplace the echo yes part by an email command

Regading leading and trailing characters you can use -C options or -A and -B (-C is -A X -B X)

   -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  Places a line containing -- between contiguous groups of matches.


   -B NUM, --before-context=NUM
          Print NUM lines of leading context before matching lines.  Places a line containing -- between contiguous groups of matches.

   -C NUM, --context=NUM
          Print NUM lines of output context.  Places a line containing -- between contiguous groups of matches.

if I understand what you want to do, you might like the following exemple

perl webinject.pl > /tmp/webinject_result.txt
if grep --quiet 'TEST CASE FAILED' /tmp/webinject_result.txt;
then
  grep -B 20 -B 2 'TEST CASE FAILED' /tmp/webinject_result.txt | mail someone@domain.tld
fi