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. thecron
spool directory and saved with the filename being same as the invoking user's name. As thecron
table is being saved for the invoking username (e.g./var/spool/cron/crontabs/foobar
, assuming usernamefoobar
); as allcron
jobs are run as that user so no username field is needed, each entry here needs 6 fields (you know these already i presume)/etc/crontab
: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 allcron
files in/etc/cron.d/
too. Another difference withcrontab -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 withcrontab -e
the file would be open with the editor mentioned asVISUAL
orEDITOR
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 inroot
'scrontab
bysudo crontab -e
or put it/etc/crontab
, i usually always prefer individual user tables.Notes:
Also
cron
uses a minimalPATH
by default, and alsoSHELL
is set assh
(dash
in Ubuntu); these two are commoncron
pitfalls.While debugging, always check
syslog
, and redirect relevant command's STDOUT and STDERR to a file for analyzing later.