自定义 stderr 附加到文件的方式

自定义 stderr 附加到文件的方式

我对使用 rsync 同步 2 个目录的 shell 脚本有疑问。我将 rsync 命令的结果(无论成功与否)存储到名为 status 的文件中,如果出现问题,stderr 输出将附加到名为 error 的文件中。但是,我似乎找不到在错误文件中实际错误之前输入时间戳的方法。

最后,我需要这样的东西:

if rsync source destination 2>> error # but I need to have the date before the actual error is appended!
then
   echo "`date` - Success" >> status
else
   echo "`date` - Failure" >> status
fi

我还尝试过以下操作:

(rsync source destination && echo "`date` - Success" >> status || echo "`date` - Failure" >> status) 2>>error

我完成这项工作的唯一方法是将 stderr 输出存储到临时文件中,以便在输入时间戳后将其内容附加到错误文件中。

答案1

你试过这个吗?

rsync -av blah blah 2>&1|perl -e "while(<>){s/^/`date`  /g; print;}" >>logfile

它将在行的开头添加日期和一些空格。

答案2

我知道自从我问这个问题以来已经过去 3 个多月了,但我认为最好能在 shell 脚本中展示我最终做了什么。

正如我所描述的,我需要以某种方式捕获 stderr,以便在日志文件中对其进行操作,例如添加时间戳。我可以使用文件并按照帕特里克的建议来完成此操作,但我想让它尽可能简单。

所以,这就是我的解决方法:

if ! result=$(command_that_will_produce_errors 2>&1 1>/dev/null)
then
    echo "There was an error on $(date): $result" >> logfile
else
    echo "Command executed successfully on $(date)" >> logfile
fi

答案3

Greg 的 Wiki 有一个条目向流的每一行添加时间戳这涵盖了多种方法,具体取决于您的环境。它们都归结为通过循环/进程管道传输流,并添加时间戳; POSIX 兼容版本是:

while IFS= read -r line; do
    echo "$(date +%Y%m%d-%H:%M:%S) $line"
done

相关内容