crontab是否有不使用编辑器(crontab -e)创建cron作业的参数?如果是,从Bash脚本创建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"
其他回答
您可以向crontab添加如下内容:
#write out current crontab
crontab -l > mycron
#echo new cron into cron file
echo "00 09 * * 1-5 echo hello" >> mycron
#install new cron file
crontab mycron
rm mycron
Cron行解释
* * * * * "command to be executed"
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
nixCraft来源。
(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
编辑(固定覆盖):
cat <(crontab -l) <(echo "1 2 3 4 5 scripty.sh") | crontab -
下面是一个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"
echo "0 * * * * docker system prune --force >/dev/null 2>&1" | sudo tee /etc/cron.daily/dockerprune