39

Is there a way to add lines to a user's cron via script?

I usually do it using crontab -e, but I would like to automate this task with a shell script.

48

You can echo the line in to the bottom of the current users crontab like this:

#!/bin/bash

line="* * * * * /path/to/command"
(crontab -u userhere -l; echo "$line" ) | crontab -u userhere -
  • +1 cuz you beat me to it (I had a script error while testing :D ). 1 thing you need to add I think: system needs to be informed that cron was changed. – Rinzwind Aug 25 '11 at 9:42
  • I knew this would be a race to get answered! You are right in that cron does need to be notified. This is why you can't just echo the command to the end of the crontab. I have tested that the above script does work and cron starts running the command. – Richard Holloway Aug 25 '11 at 9:47
  • 13
    Oh and I think this also errors out if crontab for that user does not exists yet(?) – Rinzwind Aug 25 '11 at 9:48
  • 7
    It warns you that users crontab does not exist, if that is the case, but it will then create it. I am upvoting your comments as insightful. – Richard Holloway Aug 25 '11 at 10:08
3

If you want to edit a value in your crontab, you can do something along the lines of:

$ crontab -l | sed -e 's/foo/bar/' | crontab -

Obviously you need to be careful with your substitution to be sure it only matches the line(s) you want to change; otherwise all foos are changed to bars (in this example).

The advantage to this method is that you aren't replacing the entire crontab. (A metaphorical tweezer rather than a sledgehammer.)

You can use any editing command instead of sed. For example, if you wanted to use ed to touch up a line that starts out looking like this:

2 * * * * /sbin/flitch --days 3,4 > /var/log/flitch.out 2>&1

Say this line is among many lines or you have many different crontabs to update on different systems and you only know your line is going to be the only line with the term flitch in it.

It might look like:

$ cat /tmp/edscript
/flitch
s/3/9/
w
q
$ crontab -l > /tmp/out && ed /tmp/out < /tmp/edscript && crontab - < /tmp/out
$ crontab -l
...
2 * * 1 * /sbin/flitch --days 9,4 > /var/log/flitch.out 2>&1
...

Now I must admit that nearly 100% of the time sed will do what ed will do, but it's always good to have an extra tool on the Swiss army knife. ^.^

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.