脚本在 crontab 中不起作用

脚本在 crontab 中不起作用

我注意到有很多类似的问题提出,我也尝试了发布的建议,但我似乎无法让它发挥作用。下面是我的代码。

#!/bin/bash

while IFS="" read -d "" -r filename;
do
filearray[i++]="$filename"
done < <(find . -maxdepth 1 -type f -iname "*.txt" -print0)
printf '%s\n' "${filearray[0]}"

简单来说,我只是想搜索特定目录下的所有txt类型文件,并将它们放入一个数组中,显示在最后。当我从命令行运行时,没有问题。效果很好。当我通过 crontab 执行此操作时,我收到以下错误:

syntax error near unexpected token `<'
`done < <(find . -maxdepth 1 -type f -iname "*.txt" -print0)'

这是 cron 条目本身:

* * * * * . /usr/online/scripts/test.sh 2>> /usr/online/scripts/log/test.log

为什么脚本可以在命令行上运行,但不能在 crontab 上运行?我正在声明 shell,那么 crontab 肯定应该使用 shell 吗?还有另一个为什么我可以做到这一点吗?

杰基

答案1

command < <(other command)是一个巴什主义。由于您指定了 shebang 线,因此您应该不是在 crontab 中指定一个 shell;这太令人困惑了。你应该选择其中之一 - 我非常喜欢 shebang 行,因为你明确了后面的语法,而不是假装是一个“通用”shell 脚本。

哦,确保你的脚本可执行并放置仅有的 /path/to/your/script.sh在 crontab 命令字段中,不是 sh /path/to/your/script.shsh < /path/to/your/script.sh甚至. /path/to/your/script.sh。最后三个忽略 shebang 行,而是在 cron shell 的上下文中运行脚本,无论设置是什么。

重定向指令有关将脚本输出保存到文件的更多信息。

答案2

假设该脚本是可执行的,并且从命令行调用时正在做正确的事情,请像这样编写 crontab 条目(每 15 分钟运行一次):

*/15 * * * * /path/to/script.sh >/path/to/output 2>/path/to/errors

相关内容