6

I sometimes want to output the contents of a pipe in the middle (don't we all?).

I generally do it like this (yes, I know there are other, probably better, ways):

terminal=$(tty) 
echo hello world |tee $terminal|awk '{print $2, $1}'

which outputs

hello world
world hello

Which is fine and in all respects lovely.

Except that I'd really like to do it without creating the $terminal variable. Easy, you say, just replace 'tee $terminal' with 'tee $(tty)' in the pipe, and no need for a variable? Right?

Wrong.

echo hello world |tee $(tty)|awk '{print $2, $1}'

outputs

world hello

In other words, my output from the middle of the pipe has been swallowed.

Now I accept that this is definitely a first world problem, but it annoys me and I'd like to know why the second solution doesn't work.

Anyone?

4

2 回答 2

7

如果您的系统支持它,您可以使用以下命令直接访问当前终端/dev/tty

echo hello world | tee /dev/tty | awk '{print $2, $1}'

(无论如何,该文件在 Linux 和 Mac OS X 中都可用。)

tty命令返回连接到标准输入的文件名,不一定是终端。在您的管道中,它是与前面命令的标准输出相关联的“文件”。

于 2013-05-22T14:37:11.240 回答
1

如果您的系统支持,您也可以tee与 Process Substitution 一起使用:

echo hello world | tee  >(awk '{print $2, $1}')

该行有时来得太晚,因此如果需要,您可能需要; sleep .01在末尾添加。

或者您可以使用标准错误进行报告:

echo hello world | tee >(cat >&2) |  awk '{print $2, $1}' 
于 2013-05-22T14:40:31.610 回答