1

I have written a crontab entry as:

00 19 1-7 * 3 /sbin/init 0

It should turn my linux server off on the first Wednesday of every month. Unfortunately the server went off on today (Thursday). Can anyone please tell me why it happened like this and please tell me how I can fix it.

1 Answer 1

6

From crontab(5):

   Note: The day of a command's execution can be specified by two fields --
   day of month, and day of week.  If  both  fields  are  restricted  (ie,
   aren't  *),  the command will be run when either field matches the cur-
   rent time.

This means your crontab entry won't work as expected. The command will run every day from to 1st to the 7th every month, plus every Wednesday.

Because of the above, cron alone won't be able to decide whether it's the first Wednesday of the month or not. However, you can check for one condition using cron and check for the other with test and date:

00 19 1-7 * * [ $(/usr/bin/date +\%w) = 3 ] && /sbin/init 0

How it works:

  • The command will be executed every day from the 1st to the 7th day of the month.

  • $(/usr/bin/date +\%w) returns the weekday.

  • [ ... = 3 ] && checks if that weekday is Wednesday (3).

  • If it is, /sbin/init 0 gets executed.

Note that you have to escape the percent sign, as it is special to cron.

4
  • Hi Dennis, Thank you very much for the reply. Could you please suggest me a correct way of shutting down the server at 1900 hours on first Wednesday of every month?
    – Reni
    Mar 6, 2014 at 16:58
  • I was going to post this almost an hour ago, but crontab didn't behave like I thought it would. I'm updating my answer.
    – Dennis
    Mar 6, 2014 at 17:00
  • Done. So a percent sign in the crontab indicates a comment. You live, you learn...
    – Dennis
    Mar 6, 2014 at 17:06
  • Thank you very much Dennis. Much appreciated. I will test it and update you.
    – Reni
    Mar 6, 2014 at 17:23

You must log in to answer this question.

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