I need to add a line to a user's crontab file. Normally, I would do this with crontab -e, but I want to do it with a provisioning script.

Any clever methods?


How about:

(crontab -u USERNAME -l ; echo "line to be added") | crontab -u USERNAME -

...or (although directly editing crontab files is not recommended):

echo "line to be added" >> /var/spool/cron/crontabs/USERNAME

(Assuming your provisioning script is running as root.)

| improve this answer | |
  • you can also use the environment variable $USER for the currently logged in user. – Jeff Puckett Jul 28 '16 at 21:34

There are a few ways

This will work if you want the user to edit it

echo "normal crontab line here" >> /var/spool/cron/user

If you don't want the user to edit it.. I'd drop a file into /etc/cron.d that is like

0 0 * * * username /path/to/file

You can call it whatever you want.

| improve this answer | |

Coming back to this years later, if you find yourself in this sort of situation, you should take a very close look at configuration management tools. In particular, Ansible is a great option that fits into existing infrastructure easily, and has a nice cron module.

| improve this answer | |

You could directly add new crons (if you have root privileges). you can also specify the run-as user.


| improve this answer | |
  • writing directly to the crontab file will not produce the expected results - the cron daemon needs to know about the changes – symcbean Aug 3 '11 at 12:36
  • from what I know , this works ! Assuming the script written by the user validates the cron, this is the best way ! – Sairam Aug 3 '11 at 15:44
  • 1
    @symcbean, This actually depends on "cron" implementation in use. Traditional implementations needed to be somehow informed about the changes. Many modern implementations monitor the files and pick up any changes automatically. – snap Aug 4 '11 at 7:04

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.