0
votes

Three days ago I installed the following crontab job with crontab -e:

# execute weekly
0 2 2-31 * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.log

It's supposed to be executed every sunday night at 2am except the 1st of the month. However it's executed every night at 2am. What's my mistake? I tried 0 instead of 7 for Sunday with the same result :/

Thank you.

4
Try 0 for Sunday, instead of 7? - Steve Summit
Why are you specifying 2-21 for the day? Looks like it won't run if the first of the month is a Sunday. - Steve Summit
Steve Summit, thank you. I've just edited the post to say I have already tried 0 with no success. - miganml
I think you want 0 2 * * 7 to run at 2:00am every Sunday. 7 and 0 are equivalent. (And yes, I use something just like that for once-a-week jobs.) - Dirk Eddelbuettel
2-31 because I have another job to be executed the 1st of the month so it's ok to avoid the day 1. - miganml

4 Answers

2
votes

Since the format of crontab is like this:

 +---------------- minute (0 - 59)
 |  +------------- hour (0 - 23)
 |  |  +---------- day of month (1 - 31)
 |  |  |  +------- month (1 - 12)
 |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
 |  |  |  |  |
 *  *  *  *  *  command to be executed 

To execute it every week on Sunday irrespective of the month you need to write it like this:

0 2 * * 7 sh /home/user/folder/myscript.sh week > /home/user/.crontablog/crontab.log
1
votes

first you can analyze the content of /var/log/cron, grepping for your script to see what is going on.

I suggest you use the following syntax

0 2 * * sun /home/user/folder/myscript.sh week

having given the +x permission on the script file. Cheers

0
votes

Now that you respecified your question in the comments you need to do TWO things:

  • as I said above, use 0 2 * * 7 to run at 2:00am every Sunday; 7 and 0 are equivalent

  • inside your shell script use an additional test to quietly exit on the first of the month.

That test could be as simple as

test $(date +%d) == "01" && exit

but you could of course also make it a proper if ... with more echo and verbosity.

0
votes

If you want to run the script every sunday night at 2am, but only if it's not the first day in the month, then you have to use this syntax:

0 2 * * 0 /usr/bin/test $(/bin/date +\%e) -ne 1 && your_command

The test utilliy finally check if it's the first day in month and your_command is only exected if it's not.