【问题标题】:How to use tee command in the crontab如何在 crontab 中使用 tee 命令
【发布时间】:2017-11-27 17:00:15
【问题描述】:

我在 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-23/2 语法可以替换为更标准的*/2

标签: linux bash shell crontab tee


【解决方案1】:

百分比 (%) 符号是 cron 中的特殊字符。避开 % 符号。

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 所说的话并避开那些百分比符号 (%)

    【讨论】:

      【解决方案3】:

      为什么在 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 实用程序将标准输入复制到标准输出,创建一个 复制零个或多个文件。

      【讨论】:

      • 作业没有运行,我在 cron 日志中再次遇到同样的错误:/bin/sh: -c: line 0: unexpected EOF while looking for matching `'' /bin/sh: -c:第 1 行:语法错误:文件意外结束
      • 首先在命令行运行/tmp/sample.sh > /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 2>&1
      • cron 的 PATH 非常有限。 sample.sh里面是什么@
      • 如果我只是使用0 */2 * * * /tmp/sample.sh 它的工作完美。
      • 可以,但您将无法在文件中捕获 stdout/stderr。
      【解决方案4】:

      来自您上面的 cmets

      /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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-20
        • 1970-01-01
        • 2023-03-31
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多