bash redirecting stdin to script

99封情书 提交于 2019-12-25 06:58:13

问题


I went through some bash i/o tutorials but most of them concern redirecting stream to/from files.

My problem is the following: how to redirect stdin/stdout/stderr to script (or program).

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.

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

EDIT: 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.

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.


回答1:


The pipe | is your friend:

./script1.sh | ./script2.sh

will send stdout from script1.sh to script2.sh. If you want to send stderr as well:

./script1.sh 2>&1 | ./script2.sh

And only 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 can be practically anything: EOF, !, hello, ... One thing to note though is that there cannot be any spaces / tabs infront of the end marker.

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'



回答2:


You could use the HEREDOC syntax such as:

childScript.sh -arg1 -arg2 <<EOT
input1
EOT

childScript.sh -arg1 -arg2 <<EOT
input2
EOT

And pipe to make forward the output of first script to input of second:

program1 -arg1 -arg2 | program2 -arg1 -arg9


来源:https://stackoverflow.com/questions/37549212/bash-redirecting-stdin-to-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!