user4833046
user4833046

Reputation:

bash redirecting stdin to script

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.

Upvotes: 0

Views: 686

Answers (2)

Dfaure
Dfaure

Reputation: 584

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

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47137

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'

Upvotes: 2

Related Questions