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 curr
Cron jobs usually are stored in a per-user file under /var/spool/cron
The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions (600).
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
.
Even more simple answer to you question would be:
echo "0 1 * * * /root/test.sh" | tee -a /var/spool/cron/root
You can setup cronjobs on remote servers as below:
#!/bin/bash
servers="srv1 srv2 srv3 srv4 srv5"
for i in $servers
do
echo "0 1 * * * /root/test.sh" | ssh $i " tee -a /var/spool/cron/root"
done
In Linux, the default location of the crontab
file is /var/spool/cron/
. Here you can find the crontab
files of all users. You just need to append your cronjob entry to the respective user's file. In the above example, the root user's crontab file is getting appended with a cronjob to run /root/test.sh
every day at 1 AM.
Crontab files are simply text files and as such can be treated like any other text file. The purpose of the crontab
command is to make editing crontab files safer. When edited through this command, the file is checked for errors and only saved if there are none.
crontab [path to file]
can be used to specify a crontab stored in a file. Like crontab -e
, this will only install the file if it is error free.
Therefore, a script can either directly write cron tab files, or write them to a temporary file and load them with the crontab [path to temp file]
command. Writing directly saves having to write a temporary file, but it also avoids the safety check.
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.
It is an approach to incrementally add the cron job:
ssh USER_NAME@$PRODUCT_IP nohup "echo '*/2 * * * * ping -c2 PRODUCT_NAME.com >> /var/www/html/test.html' | crontab -u USER_NAME -"