bash - 如何在将标准输出保持在屏幕上的同时通过管道传输它? (而不是输出文件)

标签 bash shell pipe output stdout

我想通过管道传输程序的标准输出,同时将其保留在屏幕上。

举个简单的例子(这里使用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/

相关文章:

bash - Git 不使用 SSH key 对 Azure DevOps 进行身份验证

bash - 有没有办法让 Go 一步编译和链接(一次 6g 和 6l)?

android - 在 android 中重命名脚本(无根)

linux - 从远程服务器查找 git 分支的名称

windows - 如何获取 Windows 中所有打开的命名管道的列表?

Bash、ffmpeg 和管道思考

linux - 使用 Linux 根据最小值/最大值过滤一个非常大的、数字排序的 CSV 文件?

linux - 在 shell 脚本中打印正确的输出

c - 如何将 bash 脚本放入 C 程序中

c# - C# 和 Delphi 之间的管道,如何让它工作?