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: the last line of a crontab needs a newline, or cron may ignore it

Cron
~/tips/tip-cron-missing-final-newline

printf '0 3 * * * /usr/local/bin/backup.sh' | crontab -

Warns that cron may treat a crontab as broken when its last line has no newline at the end.

Building a crontab from a script is tempting, and it has one trap that looks fine on the screen: the very last line.

The CAVEATS section of the cronie crontab(5) manual says that cron requires each entry in a crontab to end in a newline character. If the last entry is terminated by the end of the file instead, cron considers the crontab at least partially broken, and a warning is written to syslog.

It is easy to do by accident when you feed a crontab through a pipe. printf does not add a newline unless you ask for it:

# risky: no newline at the end
printf '0 3 * * * /usr/local/bin/backup.sh' | crontab -

# fine: the \n ends the entry
printf '0 3 * * * /usr/local/bin/backup.sh\n' | crontab -

Installing a crontab from standard input with - is documented in the synopsis of crontab(1). Be careful with this form: it replaces your whole crontab, so run crontab -l first and keep the output if there is anything in it. A safer way to add one line to an existing crontab is to append to a copy and install that file:

crontab -l > /tmp/cron.new
echo '0 3 * * * /usr/local/bin/backup.sh' >> /tmp/cron.new
crontab -T /tmp/cron.new && crontab /tmp/cron.new

echo ends its output with a newline, and crontab -T tests the syntax without installing the file. The manual says it stops at the first issue it finds, so it will not list every problem at once. I do not know whether it also catches the missing newline, so I do not rely on it for that.

The caveat is that the problem is invisible. It bites scripts and config management that write the file themselves, and the file looks perfectly normal when you print it. After installing, run crontab -l and look at the syslog for a warning from cron.

Further reading: crontab(5) manual (cronie): caveats, crontab(1) manual (cronie)

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