Crontabs are a great way of scheduling tasks. The crontab
command itself is pretty straight forward. In its basic usage, you can do:
crontab -l
– List existing crontabscrontab -e
– Edit crontabscrontab -r
– Remove all crontabscrontab -i
– Same as-r
, but with a warning prompt
Notice how e
and r
are a next to each other on the keyboard? Maybe a bit too close to each other for comfort?
I’ve lost count of the number of times I’ve accidentally removed my crontab when I wanted to edit it. Worse still, there’s no way to restore them without resorting to a backup.
Here are a couple of ways to guard against accidental deletion.
Automated Backups
The first approach is a simple solution. Add a line like the last line below:
#minute (0-59),
#| hour (0-23),
#| | day of the month (1-31),
#| | | month of the year (1-12),
#| | | | day of the week (0-6 with 0=Sunday).
#| | | | | commands
0 * * * * crontab -l > /path/to/somewhere/mycron.crontab
This writes your cron to a backup file every hour, making it easy to restore if you accidentally wipe it.
If you do delete it, you can reinstall the deleted crontab with the following:
crontab /path/to/somewhere/mycron.crontab
Meta and simple 🙂
Crontab Installation
The second approach is to never edit a crontab directly. Instead, keep the crontab in its own file. This has multiple advantages:
- Never any risk of accidental deletion
- You can use version control on it
- You can manage multiple crontabs and switch between them at will
To take this approach, create a new file with a .crontab
extension, and put your crontab there.
Now, each time you update the file, update the system crontab:
crontab mycron.crontab
Simples!
Leave a Reply