在每个月的第一个星期三关闭 Linux 服务器

1 linux crontab

我写了一个 crontab 条目:

00 19 1-7 * 3 /sbin/init 0
Run Code Online (Sandbox Code Playgroud)

它应该在每个月的第一个星期三关闭我的 linux 服务器。不幸的是,服务器今天(星期四)停机了。谁能告诉我为什么会这样,请告诉我如何解决。

Den*_*nis 6

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.
Run Code Online (Sandbox Code Playgroud)

这意味着您的crontab条目将无法按预期工作。该命令将在每个月的 1 号到 7 号的每一天以及每周三运行。

由于上述原因,单独的cron无法决定它是否是本月的第一个星期三。但是,您可以使用cron检查一个条件,并使用testdate检查另一个条件:

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

这个怎么运作:

  • 该命令将从每月的 1 号到 7 号每天执行。

  • $(/usr/bin/date +\%w) 返回工作日。

  • [ ... = 3 ] && 检查那个工作日是否是星期三 (3)。

  • 如果是,则/sbin/init 0执行。

请注意,您必须转义百分号,因为它是cron 的特殊符号。