51

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.

Sopalajo de Arrierez
  • 933
  • 3
  • 12
  • 22
Adam Matan
  • 12,289
  • 24
  • 71
  • 90

2 Answers2

68

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

#!/bin/bash

line="* * * * * /path/to/command"
(crontab -u $(whoami) -l; echo "$line" ) | crontab -u $(whoami) -
0x384c0
  • 103
  • 2
Richard Holloway
  • 29,974
  • 7
  • 52
  • 57
  • +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 09: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 09:47
  • 14
    Oh and I think this also errors out if `crontab` for that user does not exists yet(?) – Rinzwind Aug 25 '11 at 09:48
  • 9
    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
  • This saved me after so much frustration with crontab not being initialized after moving over the file via Docker commands and starting cron, but not having it ever actually work. Nice work! – Jordan Aug 01 '22 at 03:44
6

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. ^.^

fbicknel
  • 309
  • 1
  • 3
  • 10