Remember the problem caused by the wrong use of the date command in crontab

problem

I crontabadd a scheduled task as follows to move old logs to the specified directory every day:

1

0 0 * * * cd /home/vg/odp/log && mv *`date -d "-10 day" "+%Y%m%d"`* archives

Then this scheduled task does not seem to take effect. The following commands are executed separately without error.

Cause tracking

crontabFor the implementation of, Linux will send email to the corresponding user, so you can locate the problem through email. The above task is under the vg user, check the corresponding email  /var/spool/mail/vg , and find the content related to the problematic task as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

From [email protected] Tue May 14 18:00:01 2019

Return-Path: X-Original-To: vg

Delivered-To: [email protected]

Received: by MyServer.localdomain (Postfix, from userid 500)

id 694075F2AD; Tue, 14 May 2019 18:00:01 +0800 (CST)

From: [email protected] (Cron Daemon)

To: [email protected]

Subject: Cron  cd /home/vg/odp/log && mv *`date -d "-10 day" "+

Content-Type: text/plain; charset=UTF-8

Auto-Submitted: auto-generated

X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: X-Cron-Env: Message-Id: Date: Tue, 14 May 2019 18:00:01 +0800 (CST)

/bin/sh: -c: line 0: unexpected EOF while looking for matching ``'

/bin/sh: -c: line 1: syntax error: unexpected end of file

The reason for the error is clearly recorded above: it is over after unexpected EOF while looking for matching ``' reading the error report and knowing that the `command has not been matched. The problem seems strange, because the timed task command is executed separately and there is no problem. Then carefully look at the content of the email.

1

Subject: Cron cd /home/vg/odp/log && mv *`date -d "-10 day" "+

The displayed command is incomplete, and the plus sign is over. The% and the following part are lost. The reason can be basically located by combining with the error report.% is a special symbol in crontab, which means a new line starts, so the previous command is truncated.

Solution

If the command executed by crontab contains% and needs to be escaped with \, the above example can be successfully executed if it is changed to this:

1

0 0 * * * cd /home/vg/odp/log && mv *`date -d "-10 day" "+\%Y\%m\%d"`* archives

Guess you like

Origin blog.csdn.net/benli8541/article/details/112761104
Recommended