24

I am trying to find a cronjob that was created to ensure that the script doesn't duplicate the same exact cronjob.

I've been trying to use something along these lines but haven't had much luck:

if ! crontab -l | xargs grep -l '/var/www/arix/update.php'; then
  echo "Cronjob already exists"
else
  echo "Cronjob doesn't exist"
fi
user0000001
  • 2,092
  • 2
  • 20
  • 48
  • What happened after you execute these line? – Bin Wang Jan 22 '13 at 03:02
  • 2
    you don't need xargs. and why do you want `grep -l`? maybe just `if ! crontab -l | grep -q '....' ; then` should work. Finally, to debug the situation, execute inner element, then appending the next part, ie `crontab -l` (does that produce the output you expect?) then `crontab -l | ...` . Good luck. – shellter Jan 22 '13 at 03:34
  • See also https://stackoverflow.com/q/27227215/32453 – rogerdpack Apr 17 '18 at 19:17

1 Answers1

46

/var/spool/cron/crontabs is the usual parent directory for crontab files. There are files there that have names of users - root is the root crontab, for example. There is a potential for every user on the system to have used crontab -e and created his/her own crontab.

As root you can :

cd /var/spool/cron/crontabs
grep  'search string' *

This command (as root) will tell you what user's crontab has the string. And if it exists.

You would do this if if you are not sure what crontabs things are in. crontab -l only gives the stuff in YOUR crontab, the user who is currently logged in. If you are sure that is the best place to check:

crontab -l | grep -q 'search string'  && echo 'entry exists' || echo 'entry does not exist'
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • 2
    It worked! Thank you. I changed the routine to look as follows and it worked as needed. if ! crontab -l | grep -q '/var/www/arix/update1.php'; then echo "Cronjob doesn't exists" – user0000001 Jan 22 '13 at 03:41
  • Thanks @user0000001, that's a useful way to format it. – Noumenon Oct 16 '16 at 13:16