I remember learning about cronjobs in the early 2000s. I could tell the computer to go do something, on a recurring basis, forever, even when I wasn't there. They felt like magic!
We didn't have Crontab.guru or AI to ask for figuring out some of the more complex specifications. Just the man pages and good old-fashioned trial and error—mostly error in my case.
But while you could do fun, complex specifications of recurring intervals, you couldn't quite specify something quite as dynamic as "run this script every Tuesday at 7am unless it's the last Tuesday of the month..."
Or at least, you couldn't strictly through the crontab specification syntax. But I had a recent, mildly embarrassing epiphany that it's not hard at all to add arbitrary checks to your crontab to account for more complex and dynamic scenarios.
Want to run a script every Tuesday of the month at 7am except for the last Tuesday? That's easy—set up your crontab to run every Tuesday at 7am, but add a little check to make sure the next week is still part of the same month:
0 7 * * Tue [ "$(date -v+7d '+%m')" = "$(date '+%m')" ] && /path/to/your_command
If it's not part of the same month, that means we're on the last Tuesday for the month and the script won't run.
Note: The -v flag is for the macOS/BSD flavors of date . On Linux you'd want to use -d +7 days instead.
This really has nothing to do with cronjobs at all and everything to do with the POSIX "test" command which is the thing we're using with those square brackets. I'm used to seeing and utilizing them in shell scripts, but for whatever reason I never thought to reach for that tool here in the crontab.
You could just as easily rewrite it like this, skipping the bracket shorthand, which is probably easier to read:
... continue reading