Search code examples
linuxcronubuntu-16.04ubuntu-server

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?


Solution

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