9

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

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

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

I'm 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 
rogerdpack
  • 50,731
  • 31
  • 212
  • 332
fredrik
  • 7,730
  • 10
  • 56
  • 104

3 Answers3

19

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, grep will return 1, so the right hand side of the or || will be executed.

arco444
  • 19,715
  • 10
  • 57
  • 59
  • 3
    I understand that we are not supposed to edit /etc/crontab directly these days - how would we do it with crontab -e? – tofutim Mar 10 '18 at 22:42
  • 3
    (crontab -l | grep 'some_user python /mount/share/script.py') || { crontab -l; '*/1 * * * * some_user python /mount/share/script.py'; } | crontab - – PhilJ Mar 11 '20 at 22:14
  • @PhilJ why we use crontab -l before '*/1 * * * *....' ? – Estet Jan 26 '21 at 22:12
0

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
Jay Taylor
  • 11,805
  • 11
  • 55
  • 83
dleon
  • 1
0

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"

karpada
  • 165
  • 7