2

I would like to add a crontab entry from a script as a normal user, so I use sudo to get root permissions, but fails no matter what I try.

$ sudo { crontab -u root -l; echo ' 15  9  *  *  * root /opt/script.sh'; } | crontab -u root
bash: syntax error near unexpected token `}'

$ sudo echo ' 15  9  *  *  * root /opt/script.sh' >> /etc/crontab
bash: /etc/crontab: Permission denied
$ sudo echo ok
ok
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162

2 Answers2

6

Because you are running

sudo echo .......

as "su" then writing the result to /etc/crontab with:

>> /etc/crontab

so in the moment you are writing to /etc/crontab you're not "su" anymore

kappa
  • 1,559
  • 8
  • 19
1

In sudo echo ' 15 9 * * * root /opt/script.sh' >> /etc/crontab, sudo echo ' 15 9 * * * root /opt/script.sh' is ran first then the shell takes the output of the sudo command and appends it to /etc/crontab. Since the shell is started as a normal user and so doesn't have root privileges, the shell can't write to /etc/crontab, which only root can modify. To solve the problem one starts a subshell as root, which allows it to append to /etc/crontab. Fortunately, this has already been implemented as su -c, however since the system uses sudo, sudo has to be prepended. The fixed command is sudo sh -c "echo ' 15 9 * * * root /opt/script.sh' >> /etc/crontab"

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44
  • I thought the question was "Why does these sudo commands fail?" , while this answer is to the question "How can i put a line in crontab with sudo?" or "how can i run a shell command in sudo" – kappa Nov 20 '13 at 09:06
  • @kappa `"echo ' 15 9 * * * root /opt/script.sh' >> /etc/crontab` can be replaced with any other shell command. – Ramchandra Apte Nov 20 '13 at 09:24
  • sudo sh -c can be replaced by sudo -s. – petertc Oct 27 '14 at 03:37