Edit: I use Debian stable 9.3.

I have the following code which is aimed to run inside root's crontab:

0 0 * * * /opt/cron_daily.sh
0 0 * * 0 /opt/cron.weekly.sh

Of course I can manually copy it, then execute crontab -e, then pasting it in the end of the file, but what if I want to insert/inject/print this code into the root's crontab from a command instead?

Is it possible with an heredocument or some other technique?

Note: I must use crontab and not /etc/cron which as I know, are two different things.


If it matters somehow, I load the two cron scripts daily_cron.sh and weekly_cron.sh from heredocuments in Github (I copy them and paste and execute them directly in terminal).

Please show how to inject each script to daily and weekly crontabs.

  • Stephen, I wrote them myself... muru, of course it's just for the sake of testing, without m, h, dom, month, dok... – Arcticooling Jan 9 '18 at 7:55

To add those to cron, you could do the following:

echo '0 0 * * * /opt/cron_daily.sh
0 0 * * 0 /opt/cron.weekly.sh' | sudo crontab

Working on the assumption that you use Debian or derivatives, I recommend dropping the scripts in /etc/cron.daily and /etc/cron.weekly instead. Basically:

... > /etc/cron.daily/your_daily_script
... > /etc/cron.weekly/your_weekly_script
chmod 755 /etc/cron.daily/your_daily_script /etc/cron.weekly/your_weekly_script

with better names for the scripts of course (based on their purpose rather than their intended frequency).

  • Thanks Stephen. I guess it's best to give .sh as an ending and to add a scrip declaration (for example #!/bin/sh or it doesn't matter in that case? – Arcticooling Jan 9 '18 at 9:40
  • 2
    If you give them a .sh extension, they’ll be ignored (run-parts, which is used to process /etc/cron.{daily,weekly}, ignores files containing periods by default). Specifying the shebang in a shell script is always a good idea. – Stephen Kitt Jan 9 '18 at 10:01

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.