# Using sudo in a Cron Job



## rwilkerson (Nov 10, 2006)

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.


----------



## macbri (Nov 11, 2006)

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:


```
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:


```
%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.


----------



## rwilkerson (Nov 11, 2006)

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.


----------

