Greg
Greg

Reputation: 8915

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

I tried the below command and crontab stopped running any jobs: echo "@reboot /bin/echo 'test' > /home/user/test.sh"| crontab -

What is the correct way to script adding a job to crontab in linux?

Upvotes: 11

Views: 19751

Answers (3)

Mhmd
Mhmd

Reputation: 476

Im not sure about this but try this one

echo "* * * * * whatever" > /etc/crontabs/root

then check the "crontab -e" you will see your command there

For those who are using alpaine distribution , do not forget to call "crond" to make your crons start

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98861

Late answer, but on CentOS I create a new cronjob (for root, change user as needed) from a bash script using:

echo "@reboot command..." >> /var/spool/cron/root

>> will force appending to existing cronjobs or create a new cronjob file and append to it if it doesn't exist.

Upvotes: 0

McGrady
McGrady

Reputation: 11477

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.

Upvotes: 16

Related Questions