-1

I need that in the middle of a script in bash a line be executed as root, I have this code:

#!/bin/bash
...
EOF

if [[ $x = true ]] || [[ $y= "On" ]]; then
echo -e "0 8    * * *   root " >> /etc/crontab

I need the echo written in the crontab by the root user, who has a password. Currently it does not write as it is executed by the ubuntu user. Thank you.

1 Answers1

3

I propose this:

echo -e "0 8    * * *   root " | sudo tee -a /etc/crontab

When your script encounters the sudo for the tee, it will ask for your password or, if you already gave your password for sudo just recently, it will just execute the task. (Of course, if this user doesn't need to type a password for sudo, it will never ask for it.)

Using tee -a instead of shell redirection works around the fact that redirections are performed by the current shell, so adding sudo to the command will not affect the redirect (and then it will fail due to missing permissions).

Alfe
  • 56,346
  • 20
  • 107
  • 159