从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
所以第二位代码不起作用,有人可以解释一下吗?
谢谢.
解决方法:
我有一个小脚本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