5

I have a requirement to execute a script every 1st Saturday and 3rd Saturday at 8.30 AM. I am new to using the cron job in Linux. Please let me know if the following will work.

30 8 1-7,14-20 * * [ `date +\%u` = 6 ] && /path/to/myscript

Taking into consideration

  • First Saturday falls between 1 - 7
  • Third Saturday falls between 14 - 20

The cron job should run on every one of those days and immediately exit if it's not Saturday.

Please advise.

3
  • 1
    Your approach is sound I think but perhaps the second range should be 15-21? (If the month starts on Sunday, the first Saturday would be the 7th and the 14th would be the 2nd Saturday). Also = should more correctly be -eq (integer rather than string equality) Jun 3 at 14:32
  • @steeldriver You should post that as answer
    – Dan
    Jun 3 at 15:04
  • I would start the script every saturday and check inside the script and exit if it is not the 1st or 3rd.
    – Rinzwind
    Jun 3 at 15:14
5

You can probably simplify this down to:

30 8 1-7,14-20 * 6 /bin/bash /path/to/script

As per Crontab.guru, this will run At 08:30 on every day-of-month from 1 through 7 and every day-of-month from 14 through 20 and on Saturday.

7
  • Thanks. May be a dumb question . What does the /bin/bash do in this job? Jun 3 at 11:45
  • 1
    Generally one runs a cron job as root to ensure the task is performed regardless of whether you’re logged in or not. As a result, you need to specify where bash is located in order to run the script. /bin/bash is the full path to the program.
    – matigo
    Jun 3 at 12:09
  • 2
    @matigo I think the OP wants logical AND here (only on Saturdays that fall within 1-7,14-20). Your recipe will run on all days of the week between 1-7,14-20 as well as all Saturdays regardless of where they fall in the month, no? Jun 3 at 14:25
  • 1
    ... also why /bin/bash? we don't even know that /path/to/myscript is a bash script - it could be zsh or csh or python or ... . In any case, AFAIK both /bin and /usr/bin are in the default cron PATH Jun 3 at 14:28
  • Agree with @steeldriver, this will run every day between 1-7 and 14-20 and all Saturdays. crontab.guru actually confirms this if you click on the "next" link above the input.
    – Dan
    Jun 3 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.