crontab 里 % 引发的问题

写个 crontab ,命令是类似这样的

/path/to/script `date +%Y-%m-%d`

直接运行很正常,但是在 crotnab 里就出错。

/bin/sh: -c: line 1: unexpected EOF while looking for matching “’
/bin/sh: -c: line 2: syntax error: unexpected end of file

google 了好一阵才找到答案。原来 crontab 里的 % 是有特殊意义的,在这里需要转义。man 5 crontab 可以看到,

Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

% 如果没有用 转义,就会被替换成换行。所以之前的 crontab 就出错了。

解决办法:可以在 % 前面都加个 \ ,对于这个例子,写成 date +\%Y-\%m-\%d。

 

2 thoughts on “crontab 里 % 引发的问题

  1. thirdpart March 5, 2011 / 10:09 pm

    date +”%Y-%m-%d”
    Linux 或 Unix shell加上双引号可以避免被解析

  2. 车东@博客大巴 July 20, 2010 / 3:57 pm

    以前写的后台维护脚本里都有啊; 我记得咱们常用date +日期格式命令的;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s