bash将stdin重定向到脚本 [英] bash redirecting stdin to script
问题描述
我经历了一些bash I/O教程,但大多数教程都涉及将流重定向到文件或从文件重定向.
I went through some bash i/o tutorials but most of them concern redirecting stream to/from files.
我的问题如下:如何将stdin/stdout/stderr重定向到脚本(或程序).
My problem is the following: how to redirect stdin/stdout/stderr to script (or program).
例如,我有脚本"parentScript.sh".在该脚本中,我要调用黑盒"childScript.sh",该黑盒需要几个参数-arg1 -arg2 ...并从stdin读取输入.
For instance I have script "parentScript.sh". In that script I want to call blackbox "childScript.sh" which takes few arguments -arg1 -arg2 ... and reads input from stdin.
我的目标是在childScript.sh中使用parentScript.sh内的一些输入进行输入:
My goal is to feed childScript.sh with some input inside parentScript.sh:
...
childScript.sh -arg1 -arg2
????? < "input1"
????? < "input2"
...
另一种情况是我调用了几个程序,我希望它们像这样相互交谈:
Another case would be I call few programs and I want them to talk to each other like this:
...
program1 -arg1 -arg2
program2 -arg1 -arg9
(program1 > program2)
(program2 > program1)
etc...
...
如何解决这两种情况?谢谢
How to solve these 2 cases? Thanks
更具体.我想创建自己的管道(命名或未命名),并使用它们连接多个程序或脚本,以便它们彼此通信.
To be more specific. I would like to make own pipes (named or not named) and use them to connect multiple programs or scripts so they talk to each other.
例如:program1写入program2和program3并从program2接收.程序2写入程序1和程序3并从程序1接收.程序3仅接收程序1和程序2.
For instance: program1 writes to program2 and program3 and receives from program2. program2 writes to program1 and program3 and receives from program1. program3 only receives form program1 and program2.
推荐答案
管道|
是您的朋友:
./script1.sh | ./script2.sh
将从script1.sh
发送标准输出到script2.sh
.如果您也要发送stderr:
will send stdout from script1.sh
to script2.sh
. If you want to send stderr as well:
./script1.sh 2>&1 | ./script2.sh
只有stderr:
./script1.sh 2>&1 >/dev/null | ./script2.sh
您还可以在此处制作文档:
You can also make here documents:
./script2.sh << MARKER
this is stdin for script2.sh.
Variable expansions work here $abc
multiply lines works.
MARKER
./script2.sh << 'MARKER'
this is stdin for script2.sh.
Variable expansions does *not* work here
$abc is literal
MARKER
MARKER
实际上可以是任何东西:EOF
,!
,hello
,...尽管要注意的一件事是,结束标记前面不能有任何空格/制表符.
MARKER
can be practically anything: EOF
, !
, hello
, ... One thing to note though is that there cannot be any spaces / tabs infront of the end marker.
在bash中,您甚至可以使用<<<
,它的功能与此处的文档非常相似,如果有人可以澄清的话,将不胜感激:
And in bash you can even use <<<
which works much like here documents, if anyone can clarify it would be much appreciated:
./script2.sh <<< "this is stdin for script2.sh"
./script2.sh <<< 'this is stdin for script2.sh'
这篇关于bash将stdin重定向到脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!