Programmatically add entry to user's crontab

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


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.


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.