0

i am trying to write a script that will download, enable and add task with cron and then add auto update and upgrade task to the machine.

what i have until now is

sudo apt install cron
sudo systemctl enable cron 

until here all good then i add (after a research, the following commands)

<(crontab -l) <(echo '50 19 * * * sudo apt update -y') | crontab -
<(crontab -l) <(echo '00 20 * * * sudo apt upgrade -y') | crontab -

and when i check the file crontab -l

i see that the script did write the task like it should, but its not runing (i tried to run an apt install every min to see if its working)

but when i write the this command 50 19 * * 3 root sudo apt update -y with nano on that file /etc/crontab it worked

i tried to add root permeation on crontab -e but still not working

any solution?

is there is a way to add text line with script to /etc/crontab ? ( i couldn't find a way on line)

thanks you all

3
  • You need a command to concatenate <(crontab -l) and <(echo ...), and then feed that into cron using... some incantation of the crontab command. Jul 28, 2022 at 14:22
  • hey i will be happy if you can explain a lite bit more if you can
    – tops
    Jul 28, 2022 at 14:43
  • Related - Add something to crontab programmatically (over ssh). Ignore the "over ssh" part for your situation here
    – roaima
    Jul 28, 2022 at 16:15

2 Answers 2

0

On any normal system, cron should available. So the installation of cron and the enablement via systemctl should not be required. It, however, makes your script dependent on systemd while that dependency is not necessary.

Try this:

#!/bin/bash

USER=root
FILE=input.file.cron
# or get it from the command line arguments

crontab -u $USER -l | grep -v '#--$FILE:$USER' > /tmp/cr-$USER
awk '{printf("%-100s  #--$FILE:$USER\n", $$0) }' $FILE >> /tmp/cr-$USER
crontab -u $USER /tmp/cr-$USER
rm -f /tmp/cr-$USER
0

You can do this on one line by setting your editor to ed.

printf "a\n50 19 * * * sudo apt update -y\n.\nw\nQ\n" | EDITOR=ed crontab -e

Essentially, append a line to the file with your content, exit edit mode, write, and save.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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