如何在crontab中使用tee命令

5
我可以帮您进行翻译。以下是需要翻译的内容:

我在crontab中设置了一个任务,每2小时运行一次,并且我想将我的bash输出日志文件保存到一个单独的文件中。

输入:

0 0-23/2 * * * /tmp/sample.sh | tee /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt  

输出:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1: syntax error: unexpected end of file

3
“0-23/2” 可以替换为更加标准的“*/2”语法。 - fedorqui
4个回答

3

百分号(%)符号是cron中的特殊字符。请转义(escape)百分号(%)符号。

0 0-23/2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+\%Y-\%m-\%d-\%H').txt 2>&1

2

非常有理由想要这样做。如果您想的话,完全可以使用tee并仍然能够捕获输出到MAILTO。以此crontab为例:

SHELL=/bin/bash
MAILTO=someone@example.com
0 */2 * * * php /path/script.php | tee -a /path/log.$(date +"\%Y-\%m-\%d").txt

请注意Lars所说的话,并转义那些百分号符号(%)。

1

为什么在cron工作中要使用tee。为了重定向输出,您可以执行以下操作:

0 */2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 2>&1

tee 需要你的 tty 来显示输出,但是在 cron 中没有可用的 tty。

根据 man tee 的说法:

tee 实用程序将标准输入复制到标准输出,同时在零个或多个文件中做副本。


在命令行上先运行 /tmp/sample.sh > /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 2>&1 - anubhava
cron的PATH非常有限。sample.sh里面有什么? - anubhava
如果我只是简单地使用0 */2 * * * /tmp/sample.sh,那么它可以完美地工作。 - Shivam Agrawal
是的,那样做可以实现,但你将无法将标准输出/错误输出到文件中。 - anubhava
那么,使用tee命令,我可以将日志部分添加到脚本本身中吗?因为在某些情况下,我必须手动运行脚本。 - Shivam Agrawal
显示剩余2条评论

1
从您上面的评论
/tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt

问题是:/bin/sh实际上是bash吗?我见过一些操作系统它更像“类似于sh的东西”,因此bash特定的语法可能会出现问题。

0 */2 * * * /bin/bash -c '/tmp/sample.sh > /tmp/logfile_extract_$(date "+%Y-%m-%d-%H").txt 2>&1'

可能在这种情况下会起作用。或者您可以考虑使用反引号标记或从cron调用的包装器脚本,只需执行此操作即可。
/tmp/sample.sh > /tmp/logfile_extract_$(date "+%Y-%m-%d-%H").txt 2>&1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接