将带有日期的stderr重定向到来自Cron的日志文件

时间:2011-08-22 09:39:33

标签: linux bash cron stderr

从cron运行bash脚本,stderr被重定向到日志文件,这一切都正常。 代码为:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> /opt/scripts/logfile.txt

我想将日期添加到日志文件中的每一行,这不起作用,代码为:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> ( /opt/scripts/predate.sh >> /opt/scripts/logfile.txt )

predate.sh 脚本如下所示:

#!/bin/bash
while read line ; do
    echo "$(date): ${line}"
done

所以第二部分代码不起作用,有人可以解释一下吗? 感谢。

2 个答案:

答案 0 :(得分:8)

我有一个小脚本cronlog.sh来执行此操作。脚本代码

#!/bin/sh
echo "[`date`] Start executing $1"
$@ 2>&1 | sed -e "s/\(.*\)/[`date`] \1/"
echo "[`date`] End executing $1"

然后你可以做

cronlog.sh /opt/scripts/sql_fetch >> your_log_file

示例结果

cronlog.sh echo 'hello world!'

[Mon Aug 22 04:46:03 CDT 2011] Start executing echo
[Mon Aug 22 04:46:03 CDT 2011] helloworld!
[Mon Aug 22 04:46:03 CDT 2011] End executing echo

答案 1 :(得分:1)

*/10 5-22 * * * (/opt/scripts/predate.sh; /opt/scripts/sql_fetch 2>&1) >> /opt/scripts/logfile.txt

应该是你的方式。

相关问题