How do I create a crontab through a script

前端 未结 12 1036
再見小時候
再見小時候 2020-11-28 01:36

I need to add a cron job thru a script I run to set up a server. I am currently using Ubuntu. I can use crontab -e but that will open an editor to edit the curr

12条回答
  •  渐次进展
    2020-11-28 02:25

    (I don't have enough reputation to comment, so I'm adding at as an answer: feel free to add it as as comment next to his answer)

    Joe Casadonte's one-liner is perfect, except if you run with set -e, i.e. if your script is set to fail on error, and if there are no cronjobs yet. In that case, the one-liner will NOT create the cronjob, but will NOT stop the script. The silent failure can be very misleading.

    The reason is that crontab -l returns with a 1 return code, causing the subsequent command (the echo) not to be executed... thus the cronjob is not created. But since they are executed as a subprocess (because of the parenthesis) they don't stop the script.

    (Interestingly, if you run the same command again, it will work: once you have executed crontab - once, crontab -l still outputs nothing, but it doesn't return an error anymore (you don't get the no crontab for message anymore). So the subsequent echo is executed and the crontab is created)

    In any case, if you run with set -e, the line must be:

    (crontab -l 2>/dev/null || true; echo "*/5 * * * * /path/to/job -with args") | crontab -
    

提交回复
热议问题