How do I create a crontab through a script

gaurav picture gaurav · Feb 2, 2011 · Viewed 157k times · Source

I need to add a cron job thru a script I run to set up a server. I am currently using Ubuntu. I can use crontab -e but that will open an editor to edit the current crontab. I want to do this programmatically.

Is it possible to do so?

Answer

Joe Casadonte picture Joe Casadonte · Mar 8, 2012

Here's a one-liner that doesn't use/require the new job to be in a file:

(crontab -l 2>/dev/null; echo "*/5 * * * * /path/to/job -with args") | crontab -

The 2>/dev/null is important so that you don't get the no crontab for username message that some *nixes produce if there are currently no crontab entries.