文字追加到stderr在bash重定向

文字追加到stderr在bash重定向

本文介绍了文字追加到stderr在bash重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我使用exec来重定向错误输出到错误日志以

Right now I'm using exec to redirect stderr to an error log with

exec 2>> ${errorLog}

唯一的缺点是,我要开始一个时间戳每次运行以来的exec只是将文本直入日志文件。有没有一种方法来重定向标准错误,但允许我将文本追加到它,比如时间戳?

The only downside is that I have to start each run with a timestamp since exec just pushes the text straight into the log file. Is there a way to redirect stderr but allow me to append text to it, such as a time stamp?

推荐答案

这是非常有趣的。我问过谁知道bash的相当不错一个人,他告诉我是这样的:

This is very interesting. I've asked a guy who knows bash quite well, and he told me this way:

 foo() { while IFS='' read -r line; do echo "$(date) $line" >> file.txt; done; };

首先,创建了一个函数读取从标准输入原始输入的一条线,而分配到IFS使它不会忽略空白。看了一条线,它与相应的数据prepended输出它。然后,你必须告诉bash标准错误重定向到该函数:

First, that creates a function reading one line of raw input from stdin, while the assignment to IFS makes it doesn't ignore blanks. Having read one line, it outputs it with the appropriate data prepended. Then you have to tell bash to redirect stderr into that function:

exec 2> >(foo)

您写入标准错误现在一切都将通过富功能。注意当您在交互shell中做到这一点,你不会看到提示了,因为它的标准错误,并在富读取的行缓冲:)

Everything you write into stderr will now go through the foo function. Note when you do it in an interactive shell, you won't see the prompt anymore, because it's printed to stderr, and the read in foo is line buffered :)

这篇关于文字追加到stderr在bash重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:03