Is it possible to put an "if" statement in a user's crontab, or is there another sensible way to organise lots of conditional cron jobs? From the end user's perspective, it would be easiest if they could use the normal crontab and just put their entries between two lines if possible.

Ideally something like:

if [ something ]; then
* * * * * /usr/bin/php /path/to/file.php
0 0 * * * /usr/bin/php /path/to/file2.php
*/5 * * * * /root/script.sh
  • What are the conditions? Commented Oct 2, 2015 at 10:46
  • It will check whether a hostname resolves to an IP present on the system using dig. The servers are replicas and I'm trying to make sure the crons only run on the current live server.
    – James
    Commented Oct 2, 2015 at 10:59

2 Answers 2


It's not possible to do precisely this.

What you can do however, is to make a script like /usr/local/bin/check_live - which exits with status code 0 if the server is currently live, and nonzero if it's not.

You can then have crontab lines like:

* * * * * /usr/local/bin/check_live && /usr/bin/php /path/to/file.php
0 0 * * * /usr/local/bin/check_live && /usr/bin/php /path/to/file2.php
*/5 * * * * /usr/local/bin/check_live && /root/script.sh
  • A little caveat though, keep in mind that dig doesn't cache responses (which is great if you're looking to get fresh data), but that means that every crontab line with that means one DNS request per line per execution time...) - You might want to do some kind of caching yourself, or use something other than dig that can use the local resolver cache on your box. Commented Oct 2, 2015 at 17:52
  • I would have done it slightly different. Rather than having the script return a status, I would have it exec "$@" if the conditions were satisfied. Then I would remove the && from the crontab. That's just a matter of taste though, your solution is also fine.
    – kasperd
    Commented Oct 19, 2015 at 8:41
  • Exactly the sort of thing I was looking for. As an addendum, on my old server setup of two servers, only one of which was running the site database at any time, you could easily get cron jobs to run on only the server that was currently hosting mysql by using this: 33 11 * * * [ -f /var/lib/mysql/ibdata1 ] && php /path-to-script/script.php > /dev/null ...which saves you the trouble of writing a bash script, if you can depend on a file being present on only the server you want to execute the cron job on.
    – dartacus
    Commented Nov 12, 2019 at 8:45

I wouldn't recommend putting it in crontab file. Instead, create a script where you'll set your conditions and then put it in the crontab file. You'll have a much cleaner and organized setup.

  • 1
    There is not much new in this answer not already found in the accepted answer.
    – kasperd
    Commented Oct 19, 2015 at 8:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .