LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   [cron] Adding job through script? (http://www.linuxquestions.org/questions/linux-software-2/%5Bcron%5D-adding-job-through-script-864318/)

littlebigman 02-22-2011 10:58 AM

[cron] Adding job through script?
 
Hello,

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

Code:

# cat /etc/crontab
...
*/1 * * * * root /tmp/myscript.sh

# 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:
Code:

* * * * * root /tmp/myscript.sh
should work to run /tmp/myscript.sh 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"

EDIT:
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.

EDIT2:
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:
Code:

#!/bin/bash
(crontab -l 2>/dev/null; echo "* * * * * /tmp/myscript.sh") | 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/myscript.sh

Then just modify /tmp/myscript.sh 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/myscript.sh 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 05:59 PM.