crontab是否有不使用编辑器(crontab -e)创建cron作业的参数?如果是,从Bash脚本创建cron作业的代码是什么?


当前回答

Bash脚本,用于在没有交互式编辑器的情况下添加cron作业。 下面的代码帮助您使用linux文件添加cronjob。

#!/bin/bash

cron_path=/var/spool/cron/crontabs/root

#cron job to run every 10 min.
echo "*/10 * * * * command to be executed" >> $cron_path

#cron job to run every 1 hour.
echo "0 */1 * * * command to be executed" >> $cron_path

其他回答

为了用BASH脚本快速创建/替换crontab,我使用了下面的符号:

crontab <<EOF
00 09 * * 1-5 echo hello
EOF
(2>/dev/null crontab -l ; echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -
cat <(crontab -l 2>/dev/null) <(echo "0 3 * * * /usr/local/bin/certbot-auto renew") | crontab -

#输出当前crontab

crontab -l > mycron 2>/dev/null

#echo new cron到cron文件中

echo "0 3 * * * /usr/local/bin/certbot-auto renew" >> mycron

#安装新的cron文件

crontab mycron

rm mycron

所以,在Debian、Ubuntu和许多类似的基于Debian的发行版中……

有一个cron任务连接机制,它接受一个配置文件,将它们捆绑起来,并将它们添加到运行中的cron服务中。

你可以把一个文件放在/etc/cron.目录下D /somefilename,其中somefilename是你想要的任何东西。

sudo echo "0,15,30,45 * * * * ntpdate -u time.nist.gov" >> /etc/cron.d/vmclocksync

让我们来分解一下:

Sudo -因为您需要提升权限来更改/etc目录下的cron配置

Echo -在STD输出时创建输出的工具。printf,猫……也会起作用

-在你的字符串开头使用双引号,你是专业的

0,15,30,45 * * * * -标准的cron运行调度,每15分钟运行一次

ntpdate -u time.nist.gov -我想要运行的实际命令

-因为我的第一个双引号需要一个伙伴来关闭正在输出的行

>> -双重定向追加而不是覆盖*

/etc/cron.d/vmclocksync - vmclocksync是我选择的文件名,它在/etc/cron.d/


* if we used the > redirect, we could guarantee we only had one task entry. But, we would be at risk of blowing away any other rules in an existing file. You can decide for yourself if possible destruction with > is right or possible duplicates with >> are for you. Alternatively, you could do something convoluted or involved to check if the file name exists, if there is anything in it, and whether you are adding any kind of duplicate-- but, I have stuff to do and I can't do that for you right now.

我喜欢的解决方案是这样的:

(crontab -l | grep . ; echo -e "0 4 * * * myscript\n") | crontab -

这将确保您正确地处理底部的空白新行。为了避免crontab的问题,通常应该在crontab文件结束时添加一个空白的新行。上面的脚本确保它首先删除带有“grep .”部分的所有空行,然后在脚本末尾添加带有“\n”的新空行。如果现有crontab文件以空行结束,这还将防止在新命令上方出现空行。

你可以在飞行中完成

crontab -l | { cat; echo "0 0 0 0 0 some entry"; } | crontab -

Crontab -l列出当前的Crontab任务,cat打印它,echo打印新命令,Crontab -将所有打印的内容添加到Crontab文件中。您可以通过执行一个新的crontab -l来查看效果。