Is it possible to use Grep to search a file and send a email based on the results?

I have been using

grep SEARCHSTRING /logs/error_log | mailx -s subject name@emailaddress.co.uk

But I don't want it to send an email when Null it met (No results found)


You can run mailx if the grep command returns success i.e. match is found:

body="$(grep SEARCHSTRING /logs/error_log)" && echo "$body" | mailx -s subject name@emailaddress.co.uk

Saving the output of grep (if any) to variable body, if the grep command succeeds then mailx will be run with $body as the body of the mail.

output="$(grep SEARCHSTRING /logs/error_log)"
test -n "$output" && echo "$output" | mailx -s subject name@emailaddress.co.uk
  • Thank you. I never considered doing it like this, i was trying to use a Temp file to populate the results and only email when its not empty. Using the variable was a great idea. Using your example :) Thanks Changes for a one liner so can just add a Cron <BR> data=$(grep 'SEARCHSTRING' logs/error_log) ; [[ -n "$data" ]] && mail -s 'dd' name@emailaddress.co.uk <<< "$data" – Dave Hamilton Feb 3 '16 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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