How Can I Change Crontab Dynamically? [Closed]

How Can I Change Crontab Dynamically? [Closed]

I need to create a bash script in order to:

  1. Empty my root Crontab;
  2. Insert new Cronjobs via bash script.

For the first point I can use crontab -r

For the second point instead here I found this script:

#!/bin/bash

lines="* * * * * /path/to/command"
(crontab -u root -l; echo "$lines" ) | crontab -u root -

How can I cook this together in a bash script?

Something like this:

#!/bin/bash 

crontab -r 

line="* * * * * /path/to/command; 
      * * * * * /path/to/command2;
      * * * * * /path/to/command3" 

(crontab -u root -l; echo "$line" ) | crontab -u root -
9

1 Answer

The sample you posted would print current crontab and inject new directives.

If you intend to just inject new directives, wiping the current crontab, instead of your

lines="* * * * * /path/to/command"
( crontab -u root -l; echo "$lines" ) | crontab -u root -

Go with:

lines="* * * * * /path/to/command"
echo "$lines" | crontab -u root -

And, as you pointed it out in the comments, it is wrong, adding multiple crons, to use semicolons as a separator. You can go with:

lines=" line1
line2"

Or:

crontab -u root - <<EOF
line1
line2
EOF

Or:

(
    echo line1
    echo line2
) | crontab -u root -
4
David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.