gpt4 book ai didi

linux - 使用 Bash 脚本添加到 Crontab(如果不存在)

转载 作者:行者123 更新时间:2023-12-04 18:29:32 24 4
gpt4 key购买 nike

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

    最佳答案

    but running this command gives the error:

    -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失败的。

    在它前面添加一个 echo 或 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

    cron_entry=$(crontab -l 2>&1)
    is_in_cron='/mount/share/script.py'
    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 '%s\n' "$cron_entry" "$new_cron_entry" | crontab -
    fi

    关于linux - 使用 Bash 脚本添加到 Crontab(如果不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69984065/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com