CRON: Get full output only on error

I found this very handy trick to cron jobs to make sure they only e-mail you on failure, and when they do, you get the entire output of the cronjob. Thanks to this serverfault.com post

The trick is to put the entire thing including STDOUT and STDERR in a subshell outputting to variable OUTPUT, and then append || echo “$OUTPUT” to the end of the command. If the command is successful, the echo half never fires, meaning silent execution. If it does error, then the full output is echoed, which will get picked up and e-mailed from cron (if configured correctly.)

The example I used is for paperless-ngx backups:

OUTPUT=$(cd /mnt/docker/paperless && docker compose exec -T webserver document_exporter -p ../export/backup --delete 2>&1) || echo "$OUTPUT"

It works!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.