brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: chronic keeps a cron job quiet until it fails

Cron
~/tips/tip-cron-chronic-mail-on-failure

0 3 * * * chronic /usr/local/bin/backup.sh

Hides the output of cron jobs that succeed, so the mails you get always mean something.

Cron mails you whatever a job prints. A chatty backup script fills the inbox every night, so you stop reading those mails, and then you miss the one that matters.

0 3 * * *  chronic /usr/local/bin/backup.sh

chronic runs the command and keeps all its output to itself. Only when the command fails, meaning it exits with a nonzero status or crashes, does chronic print everything the command said, stdout and stderr together. No output means no mail, so a mail from cron now always means trouble.

It comes with the moreutils package, which you install first: apt install moreutils.

I think two options are worth knowing. -e also counts output on stderr as a failure, for scripts that print warnings but still exit with 0; chronic then exits with 2. -v marks which lines came from stdout and which from stderr, and shows the exit code.

The catch is that chronic trusts the exit status. A script that ends with echo done exits with 0 even when everything before it failed, and chronic stays silent. Make sure your script stops on errors, for example with set -e at the top, or ends with the exit status of the step that matters. And of course cron needs a working mail setup, or a MAILTO, for the failure output to reach you at all.

Further reading: chronic(1) manual page

Going deeper: Guide: find out why a Linux service failed, with journalctl

More Cron tips echo 'systemctl restart myapp' | at 03:00 tomorrow 55 23 28-31 * * [ "$(date -d tomorrow +\%d)" = 01 ] && /usr/local/bin/month-end.sh EDITOR=nano crontab -e 30 6 * * mon /usr/local/bin/weekly-report.sh @daily /usr/local/bin/backup.sh All Cron tips (32) All topics

Link