我想通过管道传输程序的标准输出,同时将其保留在屏幕上。
举个简单的例子(这里使用echo
只是为了说明):
$ echo 'ee' |富
ee
<- 我想看到的输出
我知道 tee 可以将标准输出复制到文件,但这不是我想要的。
$ echo 'ee' | tee 输出.txt |富
我试过了
$ echo 'ee' |发球台/dev/stdout | foo
但它不起作用,因为到 /dev/stdout
的 tee 输出通过管道传输到 foo
最佳答案
这是一个适用于任何 Unix/Linux 实现的解决方案,假设它关心遵循 POSIX
标准。它也适用于一些非 Unix 环境,例如 cygwin
。
echo 'ee' | tee /dev/tty | foo
引用:The Open Group Base Specifications Issue 7 IEEE Std 1003.1, 2013 Edition, §10.1 :
/dev/tty
Associated with the process group of that process, if any. It is useful for programs or shell procedures that wish to be sure of writing messages to or reading data from the terminal no matter how output has been redirected. It can also be used for applications that demand the name of a file for output, when typed output is desired and it is tiresome to find out what terminal is currently in use. In each process, a synonym for the controlling terminal
据报道,某些环境(例如 Google Colab)无法实现 /dev/tty
,同时仍保留其 tty
命令返回一个可用的设备。这是一个解决方法:
tty=$(tty)
echo 'ee' | tee $tty | foo
或者使用古老的 Bourne shell:
tty=`tty`
echo 'ee' | tee $tty | foo
关于bash - 如何在将标准输出保持在屏幕上的同时通过管道传输它? (而不是输出文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677201/