通过 crontab 任务移动文件不起作用,但如果手动执行则有效

Moving files through a crontab task doesn't work, but works if is executed manually

我正在尝试移动文件 crontab 以安排该计划,但 crontab 没有移动文件。如果我手动操作,它会起作用......你知道可能的原因是什么吗?这是我的:

13,29 * * * * mv $(grep -l "File was not FOUND" /home/user/test*) /home/user/temp

如果我执行以下行,它可以正常工作:

mv $(grep -l "File was not FOUND" /home/user/test*) /home/user/temp

默认情况下,cron 作业是 运行 使用 /bin/sh。您应该能够设置 shell 通过在您的工作之前添加它来使用,如下所示:

SHELL=/bin/bash
13,29 * * * * mv $(grep -l "File was not FOUND" /home/user/test*) /home/user/temp

...或您喜欢的 shell。

或者,如果您的 crond 不支持该表示法,您可以显式调用您喜欢的 shell,使用它的 -c 参数:

13,29 * * * * bash -c 'mv $(grep -l "File was not FOUND" /home/user/test*) /home/user/temp'

注意封闭的单引号。它们是必需的,因为整个命令必须是 shell.

的单个参数

另一种方法是将您的命令转换为使用普通的旧 bourne shell (sh) 语法,我认为应该是:

13,29 * * * * mv `grep -l "File was not FOUND" /home/user/test*` /home/user/temp

...使用反引号替换命令。

创建一个简单的 Schell 脚本。在顶部添加 #!/bin/bash

#!/bin/bash
mv /your/source/file/path /target/path
# In your case something like below should work.
# make sure your path is absalute path, starting from root folder.
# mv $(grep -l "File was not FOUND" /home/user/test*) /home/user/temp

然后在 crontab 中执行上述 shell 脚本,如下所示。

13,29 * * * * /path/to/file/movescript.sh

确保您的脚本具有执行权限,并且用户可以移动文件。更好的是 运行 在安排

之前手动编写脚本

chmod +x movescript.sh 将添加执行权限。