0

I'm currently working on bash script, that will add jobs to root's crontab. I'm trying to achieve it with command:

sudo crontab -e -u root | { cat; echo "@reboot /home/$CURRENT_USER/scripts/reboot.sh"; } | crontab -

I'm testing this command in shell of Ubuntu Server 18.04 and right after typing password for sudo shell hangs completely. I've tested that several times. Server resources are ok, everything works fine after establishing new ssh connection.

Please help me understand what is wrong with this command and what should I do to make it write something to roots crontab (sudo su doesn't work, because creates new shell, which stops script).

thanasisp
  • 8,122

2 Answers2

2

crontab -e invokes an editor. The output from the editor goes to the cat command, but (at best) it's waiting for you to edit the file.

You probably should do something like this

job="@reboot /home/$CURRENT_USER/scripts/reboot.sh"
tab="$(crontab -l)"
{ echo "$tab" | grep -vxF -e "$job"; echo "$job"; } | crontab

If the snippet isn't already being run as root, change both instances of the verb crontab to sudo crontab -u root

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • Why read into a variable only to echo it? And if you want to delete the job in the existing crontab before adding it at the end, use grep with -x too, and -e "$job", for safety. – Kusalananda Dec 18 '20 at 22:46
  • To avoid the possibility of a race. Much like cat Fred >Fred. Thank you for the other suggestions – Chris Davies Dec 18 '20 at 22:58
  • Most implementations would write the new crontab to a temporary file before moving it into place. In fact, that is what your code could do too if it want to be sure to preserve the integrity of the existing crontab (which echo might not do). – Kusalananda Dec 18 '20 at 23:16
-1

You don't have to use crontab to add entries to cron.

Perhaps something like:

echo "59 23 * * *  /home/$CURRENT_USER/scripts/reboot.sh" | sudo tee -a /var/spool/cron/root

cron will automatically pick up the change.

A users crontab file is just a standard text file. Manipulate it as needed and cron will pick up the changes.

mikem
  • 845
  • Why not use the defined interface (crontab)? Your code won't work unless you're already running as root – Chris Davies Dec 19 '20 at 09:23
  • yes, it doesn't work: and01admin@snd01pc04:~$ sudo echo "59 23 * * * /home/$CURRENT_USER/scripts/reboot.sh" >> /var/spool/cron/root -bash: /var/spool/cron/root: Permission denied – s-kaczmarek Dec 19 '20 at 11:31
  • sorry about that - I forgot about the wonkiness of sudo and redirects. I changed the command in my answer. Give it a try. – mikem Dec 19 '20 at 17:11