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: let cron write its environment to a file to debug a failing job

Cron
~/tips/tip-cron-dump-env-debug

* * * * * env > /tmp/cron-env.txt 2>&1

Captures the exact environment cron gives your jobs, so you can run a script the same way by hand.

The script works when you run it, and fails from cron. Nine times out of ten the difference is the environment. To see it, I’d let cron show it to you.

Add this line with crontab -e, wait a minute, then remove it again:

* * * * * env > /tmp/cron-env.txt 2>&1

The file shows what a cron job really gets. According to the man page, cron sets SHELL=/bin/sh and takes HOME and LOGNAME from the user’s entry in /etc/passwd. PATH is short, usually just /usr/bin:/bin, and the variables your login shell sets, like those from .bashrc, aren’t there.

Now you can run your script in that same environment:

env -i $(cat /tmp/cron-env.txt) /bin/sh -c '/usr/local/bin/backup.sh'

env -i starts with an empty environment and then adds only the cron variables. If the script fails now, you can see the error right in front of you instead of waiting for the next run. In the replay, the shell sees only the variables from the file.

The replay trick breaks when a value contains spaces, because the $(cat ...) splits on them. That’s rare for these variables. And don’t forget to delete the line from your crontab: it runs every minute until you do.

Further reading: crontab(5) manual page, Debian cron, env(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