Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 18 down vote accepted

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 -
share|improve this answer
    
+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
6  
Oh and I think this also errors out if crontab for that user does not exists yet(?) –  Rinzwind Aug 25 '11 at 9:48
4  
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.