首页 > 解决方案 > 使用 tee 将输入管道输入到两个进程替换

问题描述

是否可以将输入通过管道传输到两个进程替换?可以用tee做吗?还没有找到解决办法。

我有一个命令,我想使用这样的进程替换来运行:

cat input.txt | command arg1 arg2 <(command2 </dev/stdin) arg3 <(command3 </dev/stdin) arg4

我试图通过管道将输入传递给 command2 和 command3,但我发现你不能从管道中读取两次。

如果可能的话,使用 tee 执行此操作的正确语法是什么?

标签: linuxcommand-linepipeteeprocess-substitution

解决方案


也许你已经减少了你的例子太多,但你可以这样做:

cat input.txt | command arg1 arg2 <(command2 input.txt) arg3 <(command3 input.txt) arg4

或者没有猫。

<input.txt command arg1 arg2 <(command2 input.txt) arg3 <(command3 input.txt) arg4

但也许在管道之前有一个非常复杂的命令。不过,为什么不先将其保存在文件中并执行上述操作?

不过,也许输出非常大,您不想将其写入文件系统。然后,您可以使用命名管道,但有一个问题。

mkfifo input{1..3} # makes input1, input2, input3 as named pipes (!! named are still part of the file system !!)
complexcommand | tee input{1..3} & # tee will hang till it can send its output, therefor move it to the background with &
<input1 command arg1 arg2 <(command2 <input2) arg3 <(command3 <input3) arg4
rm -f input{1..3} # Since named pipes are part of the filesystem, better cleanup.

问题:根据命令的行为,以上可能会或可能不会起作用。仅当 command、command2 和 command3 同时处理数据时才有效。因此,在这种情况下,如果“command”决定在从<(command2 <input2)读取任何数据之前需要所有数据<input1,它将永远等待,因为只有在命令、命令 2 和命令 3 请求时才会发送一行。


推荐阅读