Here is another variation that I've successfully utilized for many years - capture output and print it out only on error, triggering an email. This requires no temp files, and preserves all output. The important part is the 2>&1
that redirects STDERR to STDOUT.
Send the entire output via default cron mailer config:
1 2 * * * OUTPUT=`flexbackup -set all 2>&1` || echo "$OUTPUT"
Same but with a specific address and subject:
(address can also be changed by setting MAILTO=xxxx for the entire crontab file)
1 2 * * * OUTPUT=`flexbackup -set all 2>&1` || echo "$OUTPUT" | mail -s "Failed to backup" an@email.address
You can even perform multiple actions on error and add to email:
1 2 * * * OUTPUT=`flexbackup -set all 2>&1` || {echo "$OUTPUT" ; ls -ltr /backup/dir ; }
This will work for simple commands. If you are dealing with complex pipes (find / -type f | grep -v bla | tar something-or-other
), then you're better off moving the command into a script and running the script using the aforementioned approach. The reason is that if any part of the pipe outputs to STDERR, you'll still get emails.