Using sudo in a Cron Job

rwilkerson

Registered
I find myself constantly using the locate command on my new Mac (I'm a switcher, but this seemed like a geekier question) frequently and I'd like to set up a cron job to run locate.updatedb so that my database stays reasonably current. It seems, though, that I need to run that under sudo.

Is there any way to run "sudo /usr/libexec/locate.updatedb" as a cron job? Since sudo prompts for a password, I can't figure out a way to do this. I've scanned the man pages looking for a -p (or similar) argument with no luck.

Is this possible?

Thanks.
 
Two ways, the easiest of which is probably to set up a crontab as root and then you don't need sudo in the cron job at all. Instead, you use sudo to prepare the crontab file for the root account:

Code:
sudo crontab -e

If you really do want to use sudo in the cron job you could set up sudo to not prompt for a password for that one command. With "sudo visudo" add the following line:

Code:
%admin  ALL=(ALL) NOPASSWD: /usr/libexec/locate.updatedb
(don't remove the all-important "%admin ALL=(ALL) ALL" line or you won't be able to use sudo!)
Now "sudo" will prompt your for a password for most commands but not for the /usr/libexec/locate.updatedb command.

Because an incorrectly formatted sudoers file can make it so you can't "sudo" at all, take a few precautions when doing this: make a copy of /etc/sudoers, and I usually have a second terminal open to a root shell ("sudo -s") before I muck around with the system so that if something goes pear-shaped it'll be easier to undo the damage.
 
Man, am I an idiot. I got blinded by the beautiful GUI and forgot all of my Linux basics. I can't even imagine why it didn't occur to me to just run the job itself as root.

Thank you.
 
Back
Top