2

There are certain terminal commands which can only be run as a root user. If we try to execute them without sudo keyword, they fail with the Permission denied error. An example would be a command to make a directory/folder in certain locations.

I need to run one such command as a part of a cron job in my Ubuntu 16.04. Normally I could run the command with the sudo keyword in the terminal and I would be prompted to enter the root user's password and then the command would be executed successfully.

But now that I have to enter this command as a part of a cron job in my crontab file, how do I do this? How do I run such a command as a part of a cronjob?

  • 4
    cron runs with root. You don't need to add sudo. – Pilot6 Aug 20 '17 at 11:57
  • 1
    Usually, one would put such jobs in root's crontab (sudo crontab -e rather than plain crontab -e) or use the system cron file /etc/crontab directly. Is there some particular reason you need to use a user crontab? – steeldriver Aug 20 '17 at 11:59
  • @steeldriver please what's the difference between sudo crontab -e and crontab -e? – George Udosen Aug 20 '17 at 12:02
  • 2
    @George sudo crontab -e inserts the command into root's crontab file /var/spool/cron/crontabs/root, whereas crontab -e inserts it into $USER's crontab file /var/spool/cron/crontabs/$USER – steeldriver Aug 20 '17 at 12:09
  • @steeldriver I guess my hunch was right! – George Udosen Aug 20 '17 at 12:14
5

Simply run crontab -e as root user . This would run your command with root permission and there is no need to add sudo before it .

However you can't login with root user and you need to perform your job as cron job you should specified full path in cron file :

 $ * * * * * /usr/bin/sudo /your/command

Also you can add NOPASSWD in front of your command in /etc/sudoers file to run command as root but without password .

| improve this answer | |
  • 3
    There is no need for sudo since the task will run as root already. – fkraiem Aug 20 '17 at 12:56
  • @fkraiem As i said if you don't have access to root account for making new cron as root , you can use sudo . – Ali Ghasempour Aug 20 '17 at 14:19
  • 1
    If you have access to sudo, you typically have access to root. – fkraiem Aug 20 '17 at 23:26
4

Another option is to put it in the system-wide crontab at /etc/crontab (or in a file in /etc/cron.d), where you can specify the user each task is run at:

* * * * * root mkdir /foo/bar
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.