crontab是否有不使用编辑器(crontab -e)创建cron作业的参数?如果是,从Bash脚本创建cron作业的代码是什么?
当前回答
谢谢大家的帮助。把我在这里和其他地方的发现拼凑起来,我得出了这个结论:
的代码
command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
我想不出如何在不重复自己的情况下消除对这两个变量的需求。
命令显然是我想调度的命令。Job接受$命令并添加调度数据。我需要在执行工作的代码行中分别使用这两个变量。
细节
Credit to duckyflip, I use this little redirect thingy (<(*command*)) to turn the output of crontab -l into input for the fgrep command. fgrep then filters out any matches of $command (-v option), case-insensitive (-i option). Again, the little redirect thingy (<(*command*)) is used to turn the result back into input for the cat command. The cat command also receives echo "$job" (self explanatory), again, through use of the redirect thingy (<(*command*)). So the filtered output from crontab -l and the simple echo "$job", combined, are piped ('|') over to crontab - to finally be written. And they all lived happily ever after!
简而言之:
这行代码过滤掉与命令匹配的任何cron作业,然后用新的cron作业写出剩余的cron作业,有效地充当“添加”或“更新”函数。 要使用它,您所要做的就是替换命令和作业变量的值。
其他回答
谢谢大家的帮助。把我在这里和其他地方的发现拼凑起来,我得出了这个结论:
的代码
command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
我想不出如何在不重复自己的情况下消除对这两个变量的需求。
命令显然是我想调度的命令。Job接受$命令并添加调度数据。我需要在执行工作的代码行中分别使用这两个变量。
细节
Credit to duckyflip, I use this little redirect thingy (<(*command*)) to turn the output of crontab -l into input for the fgrep command. fgrep then filters out any matches of $command (-v option), case-insensitive (-i option). Again, the little redirect thingy (<(*command*)) is used to turn the result back into input for the cat command. The cat command also receives echo "$job" (self explanatory), again, through use of the redirect thingy (<(*command*)). So the filtered output from crontab -l and the simple echo "$job", combined, are piped ('|') over to crontab - to finally be written. And they all lived happily ever after!
简而言之:
这行代码过滤掉与命令匹配的任何cron作业,然后用新的cron作业写出剩余的cron作业,有效地充当“添加”或“更新”函数。 要使用它,您所要做的就是替换命令和作业变量的值。
下面是一个bash函数,用于向crontab添加命令而不重复
function addtocrontab () {
local frequency=$1
local command=$2
local job="$frequency $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
}
addtocrontab "0 0 1 * *" "echo hello"
很有可能您正在将此工作自动化,并且您不希望单个工作添加两次。 在这种情况下使用:
__cron="1 2 3 4 5 /root/bin/backup.sh"
cat <(crontab -l) |grep -v "${__cron}" <(echo "${__cron}")
这只在使用BASH时有效。我不知道正确的DASH (sh)语法。
更新:如果用户还没有crontab,这将不起作用。更可靠的方法是:
(crontab -l ; echo "1 2 3 4 5 /root/bin/backup.sh") | sort - | uniq - | crontab -
或者,如果你的发行版支持它,你也可以使用一个单独的文件:
echo "1 2 3 4 5 /root/bin/backup.sh" |sudo tee /etc/crond.d/backup
在另一个SO问题中找到的。
不,crontab中没有修改cron文件的选项。
您必须:获取当前的cron文件(crontab -l > newfile),更改它并将新文件放置到位(crontab newfile)。
如果你熟悉perl,你可以使用Config::Crontab这个模块。
LLP安德里亚
为了用BASH脚本快速创建/替换crontab,我使用了下面的符号:
crontab <<EOF
00 09 * * 1-5 echo hello
EOF