How to Create a Crontab Through a Script

How to create a cron job using Bash automatically without the interactive editor?

You can add to the crontab as follows:

#write out current crontab
crontab -l > mycron
#echo new cron into cron file
echo "00 09 * * 1-5 echo hello" >> mycron
#install new cron file
crontab mycron
rm mycron

Cron line explaination

* * * * * "command to be executed"
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Source nixCraft.

How do I create a crontab through a script

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).

How to add a crontab job to crontab using a bash script?

I suggest you read Cron and Crontab usage and examples .

And you can run this:

➜ ( printf -- '0 4 8-14 * *  test $(date +\%u) -eq 7 && echo "2nd Sunday"' ) | crontab
➜ crontab -l
0 4 8-14 * * test $(date +\0) -eq 7 && echo "2nd Sunday"

Or

#!/bin/bash
cronjob="* * * * * /path/to/command"
(crontab -u userhere -l; echo "$cronjob" ) | crontab -u userhere -

Hope this helps.

How can I programmatically create a new cron job?

The best way if you're running as root, is to drop a file into /etc/cron.d

if you use a package manager to package your software, you can simply lay down files in that directory and they are interpreted as if they were crontabs, but with an extra field for the username, e.g.:

Filename: /etc/cron.d/per_minute

Content:
* * * * * root /bin/sh /home/root/script.sh

How can I create a crontab in a Shell script

Its not wise to operate directly with cron file. But you can add record with script like this:

crontab -l >/tmp/c1
echo '15 9 * * * /full/path/to/scripts/check_backup_include_list.sh' >>/tmp/c1
crontab /tmp/c1

If you want to remove particular record you can do for example with something like this:

crontab -l >/tmp/c1
grep -v check_backup_include_list.sh' /tmp/c1 > /tmp/c2
crontab /tmp/c2

Appending to crontab with a shell script on Ubuntu

Use crontab -l > file to list current user's crontab to the file, and crontab file, to install new crontab.



Related Topics



Leave a reply



Submit