Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 642
Greg Avatar asked Feb 13 '17 07:02

Greg


People also ask

How do I add a cron job?

You can see the contents of the user crontab with crontab -l . To add a cron job that runs as root, you can edit root's crontab by running sudo crontab -e . The most flexible way is to use the system crontab /etc/crontab which you can edit only with root privileges.


1 Answers

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.

like image 67
McGrady Avatar answered Nov 03 '22 02:11

McGrady