Why does `crontab -` remove crontab, and can it be cancelled?

I hurried and forgot the e in crontab -e before I hit Enter.

A prompt appeared, so I closed with Ctrl+D, same as I usually exit input prompts.

Now, without warning, my entire crontab is empty.

Why? What logic caused this to happen? How should I close prompts other than Ctrl+D so that nothing is saved?


Solution 1:

Control+C will in this case abort crontab and not wipe out the current crontab entries. Otherwise, the bare - is a common indication on Unix that input should be read from standard input, and Control+D closes standard input, resulting in the empty crontab file, as nothing was piped in on standard input.

A user crontab entry along the lines of

@daily crontab -l > $HOME/.cron.`hostname`

may help against any such future oopsies by providing a backup copy of the crontab data (or you can go wild with version control, or however complex you want the backup to be).

Solution 2:

You replaced your crontab with contents from stdin, which was empty. It is essentially same as crontab < /dev/null.

Pressing Ctrl+C might be a better habit.

Your crontab is most likely gone. Backup could be somewhere in /var/spool/cron, but I don't know any cron daemon that maintains backups. You should set up backups of /var/spool/cron if it's important for you.