Recover cron jobs accidently removed with crontab -r

I entered crontab -r instead of crontab -e and all my cron jobs have been removed.

What is the best way (or is there one) to recover those jobs?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

crontab -r removes the only file containing the cron jobs.

So if you did not make a backup, your only recovery options are:

  • On RedHat/CentOS, if your jobs have been triggered before, you can find the cron log in /var/log/cron. The file will help you rewrite the jobs again.
  • Another option is to recover the file using a file recovery tool. This is less likely to be successful though, since the system partition is usually a busy one and corresponding sectors probably have already been overwritten.
  • On Ubuntu/Debian, if your task has run before, try grep CRON /var/log/syslog

Method 2

If you have no /var/log/cron file you can recover the commands (but not the timings) from the syslog.

grep 'CRON.*(yourusername)' /var/log/syslog

you can then figure out most timings by looking at the datestamps.

Method 3

It sucks, but if you run crontab -r your crontab is gone forever. And unless you have a backup of it somewhere, you must grep through syslog files to get an idea of what/when jobs were being run, and recreate.

A good trick to avoid such problem is to add the following line to your crontab:

@daily          crontab -l > $HOME/.crontab

This way your crontab is backed up every day to $HOME/.crontab, so if you delete it by accident, a relatively recent copy is available and can be installed by:

crontab < $HOME/.crontab

Method 4

As an additional preventative measure in addition to backing up data, as mentioned by @anishsane, the -i flag will “prompt before deleting user’s crontab”. So, if you run crontab -i -r, it will give a nice

crontab: really delete <user>'s crontab? (y/n)

At which point you can select y or n. Of course, you don’t want to type that out every time, so put this in your bash config and forget about it:

alias crontab="crontab -i"

As the -i flag doesn’t affect any other command

Method 5

vi /var/spool/cron/*user* or if you’re the root user then vi /var/spool/cron/root


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x