Linux – Cron: only send mail if output contains string

cronemailgreplinux

Can I make cause cron to only send the email if the output (stderr) contains a certain string?

I'm aware of this answer but the command I run doesn't distinguish between stdout/stderr, it always just outputs to stdout, so I need to look for a string.

So far I got this and it basically works EXCEPT grep doesn't pass on the output to the mail command, so I just get an empty email:

0 5 * * * root mycommand | grep -q 'Renewal was done' && mail -s 'Renewal completed' my@email.com

How can I get the entire output from mycommand included in the email?

Best Answer

I would highly suggest you put the logic into a script and run that script in cron rather than try and make a one liner script in cron. That way you can easily test it outside of cron, eg:

#!/bin.bash
tmp=/tmp/t$$
mycommand > $tmp 
if grep -q 'Renewal was done' $tmp
then
    mail -s 'Renewal completed' my@email.com < $tmp
fi

rm -f $tmp
exit 0

You can add checking of mycommand exit status, pass the command being run, the string being matched and the email address in as parameters etc..