Ubuntu – Cron jobs – difference between editing “/etc/crontab” and “crontab -e”


Trying to set up a daily cron job to shut down a server.

One source suggests editing /etc/crontab

Another suggests crontab -e (with sudo)

I tried the latter, and my process did not run (if I recall, it was 30 23 * * * shutdown -h)

I also note that in the nano editor, it was working on a .tmp file? (top of nano says: /tmp/crontab.9zeTNt/crontab )

What is going on? How can I fix this?

Best Answer

crontab -e:

Usable on a per user basis; opens the cron table for the invoking user for editing (a temporary file in /tmp/ e.g. /tmp/crontab.<RANDOM>/crontab, as you have seen) and upon saving the content, sanity checkings are done. If passed, the file is moved into /var/spool/cron/crontabs/ i.e. the cron spool directory and saved with the filename being same as the invoking user's name. As the cron table is being saved for the invoking username (e.g. /var/spool/cron/crontabs/foobar, assuming username foobar); as all cron jobs are run as that user so no username field is needed, each entry here needs 6 fields (you know these already i presume)


This is the system cron table (crontab file), there is no notion of invoking user here as only superuser can edit this file, do this file needs 7 fields, with an additional username field at space/tab separated 6th field. This is true for all cron files in /etc/cron.d/ too. Another difference with crontab -e is that you need to open the file as an argument to an editor or any program/shell that can do I/O whereas with crontab -e the file would be open with the editor mentioned as VISUAL or EDITOR or /usr/bin/editor -- the first one wins.

Why your command failed inside cron:

Because shutdown can only be run as superuser or capable users, and the invoking user presumably does not fall into that category. You can put the in root's crontab by sudo crontab -e or put it /etc/crontab, i usually always prefer individual user tables.


Also cron uses a minimal PATH by default, and also SHELL is set as sh (dash in Ubuntu); these two are common cron pitfalls.

While debugging, always check syslog, and redirect relevant command's STDOUT and STDERR to a file for analyzing later.