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

发布于 2024-11-30 15:35:27 字数 550 浏览 2 评论 0原文

bash 脚本从 cron 运行,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

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

A bash script is run from cron, stderr is redirected to a logfile, this all works fine.
The code is:

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

I want to prepend the date to every line in the log file, this does not work, the code is:

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

The predate.sh script looks as follows:

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

So the second bit of code doesn't work, could someone shed some light?
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我鬧 2024-12-07 15:35:27

我有一个小脚本 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

I have a small script cronlog.sh to do this. The script code

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

Then you could do

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

Example result

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
狼性发作 2024-12-07 15:35:27
*/10 5-22 * * * (/opt/scripts/predate.sh; /opt/scripts/sql_fetch 2>&1) >> /opt/scripts/logfile.txt

应该正是你的方式。

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

should be exactly your way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文