I write a maintenance script with different commands. the script has sudo commands inside.

Now I want to use crontab, but my first problem is: How can I use the script on user level without root privilegs? Is that possible?

After that I want to copy the script on /usr/local/maintenance and want to use crontab to run the script every first thursday f.e.

EDIT: ok, I decide it now for launchD. Now I have a plist in Global Agents, it works fine. But only the user files. How can I use launchD for sudo commands?

  • This should be two questions also why do you want to copy the script and not just run it from that oath? If the script has sudo it requires raised privileges and so has to run as root or another user – mmmmmm May 30 '16 at 20:05
  • the script should also run, when the user is not in my network. Or what u mean with "why do you want to copy the script and not just run it from that oath?" I don't understand the other senteance: ok, forget root. I want to execute it with sudo but with logged user (f.e. the script delete user cache but also system cache). – D.K. May 30 '16 at 20:15
  • crontab can't execute sudo given that they are clearing caches I would write as two separate scripts one for local and one for system – mmmmmm May 30 '16 at 20:21
  • @Mark I see. And with of the scripts execute the other script? local -> system or system local. the script is like this: rm -rf ~/Library/Caches sudo rm -rf /System/Library/Caches – D.K. May 31 '16 at 7:01
  • The idea of the split is to allow one to run as root and the other as local the issue is that combining them gives you the sudo issue. So easier to use two scripts. – mmmmmm May 31 '16 at 11:47

First, the best way to run a cron script as root is to add it to the root user's crontab. EDITOR="vi" ; sudo crontab -u root -e will allow you to edit the root crontab. Once you are doing that you don't need to use `sudo; inside your script.

As for running it every Thursday, check the man page for the crontab table man crontab -s 5 and it will explain all you need to know.

  • sudo crontab -u root doesn't work. when I try crontab -e -u root I take an editor, but It doesn't save it. I try * 13 * * 5 script.sh – D.K. May 31 '16 at 6:58
  • OK, I edited the command to fix the possible problem of editing the crontab. The old version worked for me but not in a vanilla bash. – Tony Williams Jun 1 '16 at 22:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .