我在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
答案 0 :(得分:2)
百分比(%)符号是cron中的特殊字符。逃离%号。
0 0-23/2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+\%Y-\%m-\%d-\%H').txt 2>&1
答案 1 :(得分: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实用程序将标准输入复制到标准输出,制作一个 复制零个或多个文件。
答案 2 :(得分:1)
从上面的评论中
/tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt
是问题所在 1)/ bin / sh实际上是bash吗?我已经看到操作系统的“更像是一些东西”,因此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
答案 3 :(得分:1)
非常好的理由想要那个。如果您愿意并且仍然可以将输出捕获到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所说的并逃避那些百分号(%
)