-   Linux - Software (
-   -   [cron] Adding job through script? (

littlebigman 02-22-2011 10:58 AM

[cron] Adding job through script?

I need to add a job to contrab from a script. Appending the following line to /etc/crontab doesn't do anything:


# cat /etc/crontab
*/1 * * * * root /tmp/

# crontab -l
no crontab for root

Is there a way to automate adding jobs to cron?

Thank you.

d072330 02-22-2011 11:20 AM

Easiest way is to just type crontab -e as the user you want the cron job to run as and then enter your script and then save it. Then your crontab -l should list your job.

Dark_Helmet 02-22-2011 11:27 AM

Two things:

1. Your use of "*/1" is unnecessary. Unless I'm mistaken, all you need is the asterisk.

2. /etc/crontab is not root's crontab. The root user has a user-based crontab just like any other user. The /etc/crontab file and the files in /etc/cron.d are system-wide crontab files that are not associated with a specific user--they are generic "system" crontabs. They do not require use of the crontab command to install or modify.

So, appending a line to /etc/crontab, such as:

* * * * * root /tmp/
should work to run /tmp/ as root once every minute.

Note, you will not be able to see the job listed under root or any other user's crontab by using "crontab -l"

If you do not believe the script is running, then check that your script uses absolute paths to programs and/or have the script write information to a log file to verify it is working.

You can read more by using man 5 crontab -- the comments in the example crontab files explain that /etc/crontab is a "system" crontab file.

colucix 02-22-2011 11:34 AM

In alternative, if you want to update the user's crontab through script you can simply do:

(crontab -l 2>/dev/null; echo "* * * * * /tmp/") | crontab -

where redirection of standard error to /dev/null prevents the printing out of "no crontab for root" message if it is initially empty.

benq70 02-22-2011 02:05 PM

Proceed with adding your cron entry: * * * * * /tmp/

Then just modify /tmp/ to do your bidding. That way you don't need to touch your cron afterwards.

If you need to verify that your script was executed look in /var/log/cron(or equivalent) or execute "touch /tmp/myscript.`date +%m-%d-%y-%H-%M-%S`" within /tmp/ or something similar.

Long term I usually have my scripts send output to a log file for troubleshooting purposes like "echo blah blah >>/home/me/logs/logfile.log"

Hope this helps.

littlebigman 02-28-2011 06:31 AM

Thanks for the help.

All times are GMT -5. The time now is 02:03 PM.