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: crontab file.txt replaces your whole crontab, it doesn't add to it

Cron
~/tips/tip-cron-crontab-file-replaces

crontab cron.txt

Explains how installing a crontab from a file works, and how to add a line without losing the rest.

Keeping cron jobs in a file under version control is nice: you edit the file and install it with crontab cron.txt. Just know what that command does.

crontab cron.txt

It installs the file as your new crontab. Whatever was in your crontab before is gone, not merged. If the file has only the new job, every other job you had has disappeared, without a question or a backup.

So I’d always start from the current state:

crontab -l > cron.txt        # save what is there now
nano cron.txt               # change or add lines
crontab cron.txt            # install the result

To add one line from a script without opening an editor, combine the current list with the new line and feed it back through standard input, which crontab - reads:

( crontab -l 2>/dev/null; echo '15 4 * * * /usr/local/bin/report.sh' ) | crontab -

The 2>/dev/null hides the “no crontab for user” message when the crontab is still empty.

That last pattern adds the line again every time the script runs, so you get duplicates. Check first with crontab -l | grep -F report.sh, or manage the whole file in one place. For system-wide jobs, a file in /etc/cron.d is easier to install and remove, because it doesn’t touch anyone’s personal crontab.

Further reading: crontab(1) manual page, Debian cron

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