How do I create a crontab through a script How do I create a crontab through a script shell shell

How do I create a crontab through a script


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.


For user crontabs (including root), you can do something like:

crontab -l -u user | cat - filename | crontab -u user -

where the file named "filename" contains items to append. You could also do text manipulation using sed or another tool in place of cat. You should use the crontab command instead of directly modifying the file.

A similar operation would be:

{ crontab -l -u user; echo 'crontab spec'; } | crontab -u user -

If you are modifying or creating system crontabs, those may be manipulated as you would ordinary text files. They are stored in the /etc/cron.d, /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly directories and in the files /etc/crontab and /etc/anacrontab.


In Ubuntu and many other distros, you can just put a file into the /etc/cron.d directory containing a single line with a valid crontab entry. No need to add a line to an existing file.

If you just need something to run daily, just put a file into /etc/cron.daily. Likewise, you can also drop files into /etc/cron.hourly, /etc/cron.monthly, and /etc/cron.weekly.