I erased all of my cronjobs by accident due to a simple typo.

When working with cron jobs, the command crontab -e is used to edit your crontab. This command is one letter off from crontab -r, which erases your cron jobs without any confirmation prompt. On a QWERTY keyboard, the e and r keys are adjacent, which makes it especially easy to type the wrong one by accident. I accidentally typed the wrong thing, and *poof*, my cronjobs disappeared.

The fix

First, I wanted to figure out how to recover my accidentally erased cron jobs.

I found an answer on Unix StackExchange with the following helpful advice, added by an anonymous editor (typos come from the answer1):

  • On Unbuntu/debian, if your task run before you try this: grep CRON /var/log/syslog

This worked well, though I also grepped through other syslog files (on my machine, /var/log/syslog only contained entries from the past day). To do this, I un-zipped all the log files matching syslog.?.gz:

$ cd
$ ls /var/log/syslog.?.gz
/var/log/syslog.2.gz  /var/log/syslog.4.gz  /var/log/syslog.6.gz
/var/log/syslog.3.gz  /var/log/syslog.5.gz  /var/log/syslog.7.gz
$ sudo gunzip -k /var/log/syslog.?.gz

Then I copied them to my home directory and grepped through them:

$ sudo cp /var/log/syslog /var/log/syslog.? .
$ sudo chmod +r syslog*
$ grep CRON syslog* > cronlogs

I cleaned up by removing the unzipped logs:

$ rm -f syslog*
$ sudo mv /var/log/syslog.1 /var/log/syslog.1.bkp
$ sudo rm /var/log/syslog.?
$ sudo mv /var/log/syslog.1.bkp /var/log/syslog.1

Finally, I went through the list of cron job logs and manually reconstructed my entire crontab.


I came across a helpful comment on the same StackExchange post which suggests:

First thing to do, alias crontab=crontab -i.

I looked it up and found out that the -i flag makes crontab offer a confirmation prompt before removing your crontab. So, if (when) I type crontab -r again, it will prompt me to confirm that I want to remove my cron jobs. Perfect!

So I did what the comment was suggesting and added the following line to my ~/.bash_profile:

alias crontab="crontab -i"

I also found this comment in the same thread, which recommends:

0 0 * * * /usr/bin/crontab -l > ~/.crontab.bak

This is a great line to add to my crontab for extra insurance. Once a day at midnight, it will save my current crontab to a backup file.

I’m surprised that crontab is designed in such a way that this mistake is easy to make. It seems reasonable that there should be a confirmation prompt whenever one tries to delete one’s cron jobs. Fortunately, I was able to reconstruct my crontab, and I’ve taken steps to prevent this problem happening again.

  1. I submitted a suggested edit to fix the grammar after writing this post. ↩︎