gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:17:01 26 4
gpt4 key购买 nike

我有一个我想运行的脚本

$ 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com