添加到 crontab(如果尚不存在)使用 bash 脚本



bash脚本将作业添加到crontab的正确方法是什么,例如

  • 不会有重复的作业
  • 不会重新访问 crontab 文件
  • (可选)接近单行

在下面遇到了这个解决方案,但它不会影响运行crontab -l的输出。

grep 'some_user python /mount/share/script.py' /etc/crontab || echo '*/1 *  *  *  * some_user python /mount/share/script.py' >> /etc/crontab

尝试将其转换为影响crontab -l

(crontab -l | grep '/mount/share/script.py') || { crontab -l; '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

但是运行此命令会出现错误:

-bash: */1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1: No such file or directory

但运行此命令会出现错误:

-bash: */1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1: No such file or directory

代码:

(crontab -l | grep '/mount/share/script.py') || { crontab -l; '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

将尝试执行/运行:

'*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'

如果以及何时grep失败。


在其前面或 printf 添加一个回显,因为crontab需要来自stdin的输入,就像您在第一个示例/代码中所做的那样,如下所示:

(crontab -l | grep '/mount/share/script.py') || { crontab -l; echo '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

这是一个替代方案,它是一个完整的脚本。

#!/usr/bin/env bash
is_in_cron='/mount/share/script.py'
cron_entry=$(crontab -l 2>&1) || exit
new_cron_entry='*/1 * * * * some_user python /mount/share/script.py >> /tmp/foo/logs/foo.cron.log 2>&1'
if [[ "$cron_entry" != *"$is_in_cron"* ]]; then
printf '%sn' "$cron_entry" "$new_cron_entry" | crontab -
fi

相关内容

  • 没有找到相关文章

最新更新