bash - 如何在 bash 脚本中 fork /管道标准输入?

标签 bash pipe stdin

我有一个我想运行的脚本

$ myscript < mydata.dat

myscript 中,我需要将 STDIN fork /传输到多个目的地

#!/usr/bin/env bash

php script1.php > out1
php script2.php > out2
php script3.php > out3

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

有点像

# obviously this is broken ...
STDIN | php script1.php > out1
STDIN | php script2.php > out2
STDIN | php script3.php > out3

最佳答案

要将标准输入复制到多个进程,请使用tee进程替换:

tee >(script1 > out1) >(script2 >out2) ... | lastscript >outlast

构造>(...) 称为进程替换。它创建一个 tee 可以写入的类文件对象。 parens 中的命令被执行,无论 tee 写入什么,都会作为标准输入提供给命令。

进程替换 受 bash、ksh 和 zsh 支持。它不是 POSIX,不能在破折号下工作。

简单例子

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

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

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

$ seq 10 | bash myscript
$ cat out1
1
10
$ cat out2
2
$ cat out3
3

关于bash - 如何在 bash 脚本中 fork /管道标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39759394/

相关文章:

c - 卫生间 : standard input: Bad file descriptor

java - 与 DriverManager 中的 GetConnection() 方法和 Scanner、System.in 中的 next() 方法相关的线程死锁

mysql - 将命令输出重定向到 mysql

带有字段分隔符和最后一个条目换行符的 BASH printf 数组

linux - 如何区分 $1 作为 shell 变量和 $1 作为 awk 变量?

linux - Bash fork 子 shell

javascript - RXJS 链依赖的 observables 顺序,但获取进度条的每个发射

c - 通过管道向 mplayer 发送数据时程序崩溃

c# - 如何使用 sendmessage(C#) 向 cmd.exe 发送退格键

python - 使用管道运算符在两个Python脚本之间流式传输多批数据