2016-05-31 85 views
0

我經歷了一些bash i/o教程,但其中大多數都涉及將文件重定向到/來自文件。bash重定向標準輸入到腳本

我的問題是以下內容:如何將stdin/stdout/stderr重定向到腳本(或程序)。

例如我有腳本「parentScript.sh」。在那個腳本中,我想調用blackbox「childScript.sh」,它只需要很少的參數-arg1 -arg2 ...並從標準輸入讀取輸入。

我的目標是與內部parentScript.sh一些輸入養活childScript.sh:

... 
childScript.sh -arg1 -arg2 
????? < "input1" 
????? < "input2" 
... 

另一種情況是我所說的幾個節目,我希望他們能夠相互交談像這樣:

... 
program1 -arg1 -arg2 
program2 -arg1 -arg9 
(program1 > program2) 
(program2 > program1) 
etc... 
... 

如何解決這兩種情況?謝謝

編輯: 更具體的。我想製作自己的管道(命名或不命名),並使用它們連接多個程序或腳本,以便彼此交談。

例如:program1寫入program2和program3並從program2接收。程序2寫入程序1和程序3並從程序1接收。 program3只接收表格program1和program2。

+0

可能的重複http://stackoverflow.com/questions/1987105/bash-redirect-standard-input-dynamically-in-a-script – Inian

+1

現在,這可以說是太廣泛了。程序化流水線構建的許多技術(例如遞歸函數執行組件)是否適用取決於您未提供的細節。[另外,在已經提供了答案之後,以一種能夠顯着改變其含義的方式「澄清」一個問題並不是特別好的形式,因爲它使得那些先前的答案沒有用處]。 –

+0

好點。我會做新的線程 – tomtom

回答

2

管道|是你的朋友:

./script1.sh | ./script2.sh 

將從script1.sh發送到標準輸出script2.sh。如果你想發送標準錯誤,以及:

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

而且只有標準錯誤:

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

你也可以在這裏做文件:

./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,...但有一點需要注意的是,不能有任何空格/製表符在結束標記的前面。

而且在bash,那麼你甚至可以使用<<<它的工作原理非常喜歡這裏的文件,如果任何人都可以澄清這將是大加讚賞:

./script2.sh <<< "this is stdin for script2.sh" 
./script2.sh <<< 'this is stdin for script2.sh' 
+0

請參閱編輯 – tomtom

0

您可以使用定界符語法如:

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

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

和管道進行着第一個腳本的輸出的第二輸入:

program1 -arg1 -arg2 | program2 -arg1 -arg9 
+0

請參閱編輯 – tomtom