如何在bash脚本中fork/pipe stdin?

Tha*_*you 3 bash stdin pipe

我有一个我想要运行的脚本

$ myscript < mydata.dat
Run Code Online (Sandbox Code Playgroud)

在里面myscript我需要将STDIN分叉/管道到多个目的地

#!/usr/bin/env bash

php script1.php > out1
php script2.php > out2
php script3.php > out3
Run Code Online (Sandbox Code Playgroud)

每个人都需要一份STDIN.可能吗?

就像是

# obviously this is broken ...
STDIN | php script1.php > out1
STDIN | php script2.php > out2
STDIN | php script3.php > out3
Run Code Online (Sandbox Code Playgroud)

Joh*_*024 8

要将stdin复制到多个进程,请使用tee处理替换:

tee >(script1 > out1) >(script2 >out2) ... | lastscript >outlast
Run Code Online (Sandbox Code Playgroud)

该构造>(...)称为过程替换.它创建了一个tee可以写入的类文件对象.parens中的命令被执行,并且tee对它的任何写入都作为stdin提供给命令.

bash,ksh和zsh支持进程替换.它不是POSIX,不会在短划线下工作.

简单的例子

让我们考虑一下这个简单的脚本:

$ cat myscript 
#!/bin/bash
tee >(grep 1 >out1) >(grep 2 >out2) | grep 3 >out3
Run Code Online (Sandbox Code Playgroud)

我们可以运行它并验证结果:

$ seq 10 | bash myscript
$ cat out1
1
10
$ cat out2
2
$ cat out3
3
Run Code Online (Sandbox Code Playgroud)