将 bash 输出通过管道传输到两个不同的流
我有一个 bash 脚本,它通过 ssh 在两台不同的机器上生成进程,然后将其中一个的输出放入文本文件中。如何在终端运行时也显示输出?
I have a bashscript that spawns processes on two different machines over ssh and then cat's the output of one into a text file. How can I have the output ALSO displayed in the terminal as it's running?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看
tee
实用程序 (man tee
)。Look at the
tee
utility (man tee
).当您想要将流保存到文件并继续处理它时,tee 命令非常有用。但是,如果要将 stdout 发送到两个单独的程序,可以使用 while read 循环并将输出回显到 stdout 和 stderr,然后将 stdout 流式传输到一个程序,将 stderr 流式传输到另一个程序。
这是一个演示,其中字符串“input”前面加上一个数字以显示输出的去向,然后作为输入发送到两个 perl 程序,这两个程序只是在前面加上流名称。
输出是
警告 - while/read/echo 可能不会保留行结尾和二进制文本,长行会导致问题。与许多事情一样,bash 可能不是最好的解决方案。这是一个 Perl 解决方案,适用于除非常大的文件之外的任何内容:
The
tee
command is great when you want to save a stream to a file and continue processing it. However, if you want to send stdout to two separate programs, you can use a while read loop and echo the output to stdout and stderr and then stream stdout to one program and stderr to another.Here is a demo where the string "input" is prepended with a number to show where the outputs are going, and then sent as input to two perl programs that simply prepend the stream name.
output is
Caveat - the while/read/echo thing may not preserve line endings and binary text, and long lines will cause problems. As with many things, bash may not be the best solution. Here is a perl solution for anything but really huge files: