MacOS – Root crontab won’t save

bashcronmacosterminal

I'm trying to add a crontab entry to my root user's crontab. I'm able to add an entry without issue to my regular user's crontab, but when I su to root user and try adding a crontab entry it does not save the entry.

The process I'm going through is:

$sudo su
$crontab -e
# write out my crontab entry and then :wq to write and quit vi
$crontab -l
crontab: no crontab for root

I've also tried exiting vi using wq! and it still will not save the entry.

The entry that I'm entering is:

* * * * * /sayhi.sh

sayhi.sh is a simple shell script I'm using to try to verify that the cron job is running.

Is there something different I need to do if I'm trying to create a crontab entry for root? I've been looking around and I haven't seen anything about crontab that's particular to the root user.

Any help would be appreciated!

Best Answer

Your commands should actually work, however it's not as I would do it.

Instead try :-

sudo crontab -e -u root

then to list :-

sudo crontab -l -u root

As a general rule I go to a great deal of trouble to never run a root shell. When I do I use sudo -s rather than sudo su.

When you exit from vi you should see two lines :-

crontab: no crontab for root - using an empty one
crontab: installing new crontab

If you don't get those two lines you have serious troubles. If you do and then the list command doesn't show anything I would suspect permission troubles.

I also wouldn't use your example line as you are asking the system to run "sayhi.sh" once a minute all day, every day. I also wonder about the path "/sayhi.sh" - do you really have the script right up the top of your boot drive? That's not a good idea either or do you perhaps mean "~/sayhi.sh" which in this case would be in roots home directory (usually /var/root) or do you mean your home directory. In crontab files it's best to explicitly code the entire path, regardless.

You do also realise that tany output of the cron job will not go to any terminal but will instead be emailed to root (by default).

If you want to check that cron is running tasks a simple

*/5 * * * *   echo "CRON" > /Users/myname/.cronout

will do that (the first field runs the task a much more reasonable every 5 minutes).

The crontabs themselves are stored in /usr/lib/cron/tabs. /usr/lib/cron is actually a link to /var/at and if you go there you will find the tabs directory and also the cron.deny file. Check that nobody has added root to that and if you still have no joy then you might try :

echo > /var/at/tabs/root

which should create an empty file that you might then be able to edit.