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

标签 linux bash cron stderr

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

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

最佳答案

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

关于linux - 将带有日期的 stderr 重定向到来自 Cron 的日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145544/

相关文章:

bash - 使用 `env` 命令并通过文件传递环境变量的最佳方法

linux - bash计算器代码解释

regex - 更好的 bash 脚本来创建目录结构

linux - Ping 状态和返回

python - python 错误: name '...' is not defined

macos - OS X 上的 Bash 区域设置敏感通配符

ruby-on-rails - 无法在 rails 3 中使用任何时候运行 cronjob

linux - 如何将无限 nc (netcat-openbsd) 作业添加为 crontab -e 命令以运行 @restart?

cron - OpenERP 和 Gunicorn

c++ - 是否可以强制Linux在释放后使虚拟内存失效