Nov 06 2009

Cron中的最常见错误。。。

Category: 技术ssmax @ 12:29:53

一个常见的错误是,命令行双引号中使用%时,未加反斜线\,例如:

# 错误的例子:
1 2 3 4 5 touch ~/error_`date "+%Y%m%d"`.txt

在守护进程发出的电子邮件中会见到错误信息:

/bin/sh: unexpected EOF while looking for `'''''''
# 正确的例子:
1 2 3 4 5 touch ~/right_$(date +\%Y\%m\%d).txt

# 使用单引号也可以解决问题:
1 2 3 4 5 touch ~/error_$(date '+%Y%m%d').txt

# 使用单引号就不用加反斜线了。这个例子会产生这样一个文件 ~/error_\2006\04\03.txt
1 2 3 4 5 touch ~/error_$(date '+\%Y\%m\%d').txt

下例是另一个常见错误:

# Prepare for the daylight savings time shift
59 1 1-7 4 0 /root/shift_my_times.sh

初看似要在四月的第一个星期日早晨1时59分运行shift_my_times.sh,但是这样设置不对。

与其他域不同,第三和第四个域之间执行的是“或”操作。所以这个程序会在4月1日至7日以及4月余下的每一个星期日执行。

这个例子可以重写如下:

# Prepare for the daylight savings time shift
59 1 1-7 4 * test `date +\%w` = 0 && /root/shift_my_times.sh

另一个常见错误是对分钟设置的误用。下例欲一个程两个小时运行一次:

# adds date to a log file
* 0,2,4,6,8,10,12,14,16,18,20,22 * * * date >> /var/log/date.log

而上述设置会使该程序在偶数小时内的每一分钟执行一次。正确的设置是:

# runs the date command every even hour at the top of the hour
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * date >> /var/log/date.log
# an even better way
0 */2 * * * date >> /var/log/date.log

2 Responses to “Cron中的最常见错误。。。”

  1. brisbane says:

    太谢谢了。。。
    我就经常犯这些错误。。。

  2. sexla says:

    说实话,我看不懂!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.