将条目插入到crontab中,除非它已经存在(如果可能的话,作为单行代码)

时间:2014-12-01 11:17:04

标签: bash centos6

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

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

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

我在使用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 

3 个答案:

答案 0 :(得分:14)

你可以这样做:

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

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

答案 1 :(得分:0)

你可以这样做:

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

甚至更简洁:

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

答案 2 :(得分:0)

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