Bash – Have cron email output to MAILTO based on exit status

bashcron

I have a cron job running a php command like this:

php /path/to/script.php > dev/null

This should send only STDERR output to the MAILTO address. From what I gather the php script is not outputting any STDERR information even when its exit status is 1.

How can I get the output of the php command (STDOUT) and only send it to MAILTO if the exit status is non-zero?

Best Answer

php /path/to/script.php > logfile || cat logfile; rm logfile

which dumps standard output into logfile and only outputs it if the script fails (exits non-zero).

Note: if your script might also output to stderr then you should redirect stderr to stdout. Otherwise anything printed to stderr will cause cron to send an email even if the exit code is 0:

php /path/to/script.php > logfile 2>&1 || cat logfile; rm logfile
Related Question