Insert a record in crontab if it already does not exist (if possible, as a single line)

What is the preferred way to insert an entry in / etc / crontab if it does not exist, preferably using a single line?

Here is my sample entry that I want to place in / etc / crontab if it does not already exist there.

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

I am on CentOS 6.6, and so far I have this:

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 
+4
source share
3 answers

You can do it:

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

If there is no line, it grepwill return 1, so the right-hand side or will be executed ||.

+11
source

You can do it as follows:

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 concise:

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

q F file="/etc/crontab"; grep -qF "some_user python /mount/share/script.py" "$file" || echo "*/1 * * * * some_user python /mount/share/script.py"

0
source

All Articles