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.


2 Answers 2


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


line="* * * * * /path/to/command"
(crontab -u $(whoami) -l; echo "$line" ) | crontab -u $(whoami) -
  • +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, 2011 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. Aug 25, 2011 at 9:47
  • 14
    Oh and I think this also errors out if crontab for that user does not exists yet(?)
    – Rinzwind
    Aug 25, 2011 at 9: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. Aug 25, 2011 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 1, 2022 at 3:44

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .