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: cron has no last day of the month, but a date check gives you one

Cron
~/tips/tip-cron-last-day-of-month

55 23 28-31 * * [ "$(date -d tomorrow +\%d)" = 01 ] && /usr/local/bin/month-end.sh

Runs a cron job on the last day of every month, whatever its length.

Monthly invoices or reports often belong on the last day of the month. Standard cron can’t say that, because months end on the 28th, 29th, 30th or 31st.

The trick is to run every day at the end of the month and let the command check whether tomorrow is the 1st:

55 23 28-31 * *  [ "$(date -d tomorrow +\%d)" = 01 ] && /usr/local/bin/month-end.sh

cron starts the line on days 28 to 31. date -d tomorrow +%d prints tomorrow’s day of the month, and only when that’s 01 does the && let the script run. You can check the logic with a fixed date: for 30 November, the day after gave 01, so the test passed.

The backslash before % matters. In a crontab, a bare percent sign is turned into a newline, which would cut the command in half. On the command line you’d type +%d without it.

date -d is GNU date, which every normal Linux has. BusyBox date in Alpine-based images and the date on macOS work differently, so this exact line fails there. Also note the time: 23:55 leaves only five minutes before midnight. If the job can take longer and needs the month to still be the same, run it earlier in the day.

Some cron implementations have an L for the last day, but Debian’s cron and cronie don’t, so I’d stick with the date check.

Further reading: crontab(5) manual page, Debian cron, date(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 EDITOR=nano crontab -e 30 6 * * mon /usr/local/bin/weekly-report.sh @daily /usr/local/bin/backup.sh sudo ls -l /var/spool/cron/crontabs All Cron tips (32) All topics

Link