通过 Bash 脚本编辑 crontab

问题描述 投票:0回答:1

仅当 crontab 条目不存在时,我才需要添加它。但由于某种原因,我根本无法为此编写简单的脚本。

我已经尝试过这段代码(以及许多其他建议),但它总是附加到现有的 crontab 中。如果我尝试用“if else fi”表达一切,什么都不会改变。我在 Bash 中不明白什么?

#!/bin/bash
set_cron() {
    # get the current crontab entries
    crontab -l > cron
    # set up new crontab entries
    cron_cmd="0 0 5 * * prosodyctl --root cert import /etc/letsencrypt/live/"
    # append new crontab entries if needed
    grep -q "$cron_cmd" cron || echo "$cron_cmd" >> cron && crontab cron && rm cron
}
set_cron
bash
1个回答
0
投票

*
中的
$cron_cmd
在正则表达式中具有特殊含义。使用
-F
选项搜索固定字符串而不是正则表达式。

if ! grep -F -q "$cron_cmd" cron; then
    echo "$cron_cmd" >> cron && crontab cron && rm cron
fi
© www.soinside.com 2019 - 2024. All rights reserved.