bash 将条目插入 crontab 除非它已经存在(如果可能,作为单行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27227215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:55:28  来源:igfitidea点击:

Insert entry into crontab unless it already exists (as one-liner if possible)

bashcentos6

提问by fredrik

What's the preferred method to insert an entry into /etc/crontab unless it exists, preferably using a one-liner?

将条目插入 /etc/crontab 的首选方法是什么,除非它存在,最好使用单行?

Here's my example entry I wish to place into /etc/crontab unless it already exists in there.

这是我希望放入 /etc/crontab 的示例条目,除非它已经存在于那里。

*/1 *  *  *  * some_user python /mount/share/script.py

I'm on CentOS 6.6 and so far I have this:

我在 CentOS 6.6 上,到目前为止我有这个:

if grep "*/1 *  *  *  * some_user python /mount/share/script.py" /etc/crontab; then echo "Entry already in crontab"; else echo "*/1 *  *  *  * some_user python /mount/share/script.py" >> /etc/crontab; fi 

回答by arco444

You can do this:

你可以这样做:

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

If the line is absent, grepwill return 1, so the right hand side of the or ||will be executed.

如果该行不存在,grep将返回1,因此||将执行or 的右侧。

回答by dleon

You can do it like this:

你可以这样做:

if grep "\*\/5 \* \* \* \* /usr/local/bin/test.sh" /var/spool/cron/root; then echo "Entry already in crontab"; else echo "*/5 * * * * /usr/local/bin/test.sh" >>  /var/spool/cron/root; fi

Or even more terse:

或者更简洁:

grep '\*\/12 \* \* \* \* /bin/yum makecache fast' /var/spool/cron/root \
    || echo '*/12 * * * * /bin/yum makecache fast' >> /var/spool/cron/root

回答by karpada

Factoring out the filename & using the q & F options file="/etc/crontab"; grep -qF "some_user python /mount/share/script.py" "$file" || echo "*/1 * * * * some_user python /mount/share/script.py"

分解出文件名并使用 q & F 选项 file="/etc/crontab"; grep -qF "some_user python /mount/share/script.py" "$file" || echo "*/1 * * * * some_user python /mount/share/script.py"