如果已经存在,如何避免设置cron

时间:2018-04-12 10:08:06

标签: linux bash shell cron

我正在使用以下命令设置一个cron

crontab -l | { cat; echo -e "#Adding cron task to execute imz script \n0 */1 * * * /usr/local/sbin/generate_imz_report.sh"; } | crontab -

通过shell脚本。每次我执行脚本时,都会为此脚本添加一个新条目

xyx.local: ~ # crontab -l
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh
#Adding cron task to execute imz script
0 */1 * * * /usr/local/sbin/generate_imz_report.sh

为避免这种情况,我尝试了以下

grep '#Adding cron task to execute imz script' /etc/crontab || crontab -l | { cat; echo -e "#Adding cron task to execute imz script \n0 */1 * * * /usr/local/sbin/generate_imz_report.sh"; } | crontab -

但这不起作用。如果已经存在于shell脚本中,我如何避免添加cron条目?

2 个答案:

答案 0 :(得分:0)

如果要添加的cron作业已经存在,则需要检查cron文件

SCRIPT="generate_imz_report.sh"
if crontab -l | grep $SCRIPT > /dev/null ; then
    echo "Cron job already installed."
else
    crontab -l > newcronjobs                                       # Write out old crontab
    echo "0 */1 * * * /usr/local/sbin/$SCRIPT" >> newcronjobs      # Append new cron job into cron file
    crontab newcronjobs                                            # Install new cron file
    rm newcronjobs
    echo "New cron job is added to crontab!!"
fi

答案 1 :(得分:0)

您确定crontab文件“/ etc / crontab”的位置吗? 你为什么不试试

$( crontab -l | grep 'generate_imz_report' ) || crontab -l | { cat; echo -e "#Adding cron task to execute imz script \n0 */1 * * * /usr/local/sbin/generate_imz_report.sh"; } | crontab -