tee 命令通过 grep 管道传输并重定向到文件

tee command piped in a grep and redirected to file

我想在 bash 中使用以下命令:

(while true; do date; sleep 1;done) | tee out.out 2>&1 | grep ^[A-Z] >log.log 2>&1 &

不幸的是,在它完成之前(例如通过杀死 sleep 命令的 ppid),文件 log.log 是空的,但文件 out.out 具有预期的内容。

  1. 我首先想了解发生了什么
  2. 我想解决这个问题。

为了解决这个问题,您需要 grep 行缓冲。这可能取决于实现,但在 BSD grep(随 Mac OS X 一起提供)上,您只需将 --line-buffered 选项添加到 grep:

(while true; do date; sleep 1;done) | tee out.out 2>&1 | grep --line-buffered ^[A-Z] >log.log 2>&1 &

来自 grep 手册页:

--line-buffered
             Force output to be line buffered.  By default, output is line buffered when standard output is a terminal and block buffered otherwise.

您实际上可以通过输出到 STDOUT 来验证该行为:

(while true; do date; sleep 1;done) | tee out.out 2>&1 | grep ^[A-Z] 2>&1 &

在那种情况下,您不需要明确地逐行缓冲,因为这是默认设置。但是,当您重定向到一个文件时,您必须明确设置该行为。