2014-09-24 77 views
0

這是我上一個關於SO的問題的後續。我仍然試圖從另一個腳本shallowScript中命令腳本deepScript,並在顯示在終端上之前處理其輸出。下面是一個代碼示例:重定向/管道讀取命令

deepScript.sh

#!/bin/zsh 
print "Hello - this is deepScript" 
read "ans?Reading : " 
print $ans 

shallowScript.sh

#!/bin/zsh 

function __process { 
    while read input; do 
     echo $input | sed "s/e/E/g" 
    done } 

print "Hello - this is shallowScript" 
. ./deepScript.sh |& __process 

(編輯:此語法的和的2層的替代結果粘貼下面)

[UPDATE]

我已經嘗試了最後一次重定向的替代語法. ./deepScript.sh |& __process,每種語法都有不同的結果,但當然沒有一個是我想要的。我將粘貼每個語法和結果輸出./shallowScript.sh(當我輸入read等待輸入時,我輸入「input」)以及目前爲止的結果。

選項1:. ./deepScript.sh |& __process

從這個link,似乎. ./deepScript.sh從子shell運行,但不__process。輸出:

zsh : ./shallowScript.sh 
Hello - this is shallowScript 
HEllo - this is dEEpScript 
input 
REading : input 

基本上,前兩行被打印爲期望值,則而不是打印的提示REading :,腳本直接等待stdin的輸入,並且然後打印提示,並執行print $ans

選項2:__process < <(. ./deepScript.sh)

Zsh的manpage表明(. ./deepScript.sh)將運行一個子進程。對我來說,這看起來類似於選項1。輸出:

Hello - this is shallowScript 
Reading : HEllo - this is dEEpScript 
input 
input 

所以,. ./deepScript.sh,它打印讀取的打印(腳本行2)前提示(腳本行3)。奇怪。

方案3:__process < =(. ./deepScript.sh)

根據同manpage(. ./deepScript.sh)這裏將其輸出到一個臨時文件,然後在注射__process(我不知道是否有子與否) 。輸出:

Hello - this is shallowScript 
Reading : input 
HEllo - this is dEEpScript 
input 

同樣,deepScript的第3行打印到第2行之前的終端,但現在它等待讀取完成。

兩個問題:

  • 如果有這樣的預期?
  • 有沒有修復或解決方法?

回答

1

所觀察到的延遲源於兩個因素:

  1. deepScript.sh和異步
  2. readprocess運行讀取一個完整的行返回

deepScript.sh寫入提示標準錯誤之前,但沒有換行符。然後等待您的輸入,而process繼續等待完整的一行寫入,以便其可以完成對read的呼叫。

+0

chepner,有沒有可以推薦的解決方法? – 2014-09-28 11:09:47

+0

我建議不要試圖同時處理標準輸出和標準錯誤。它們是兩個獨立的流,並且任何嘗試合併它們(通過將它們都連接到相同的命令中)將使它們以非確定性方式交錯。 '__process' *真的需要處理兩者嗎? – chepner 2014-09-28 20:45:00

+0

其實,我之所以想到這個問題的唯一原因是因爲'read'會將其提示打印到stderr(至少zsh的內置讀取)。但我可以沒有這種生活;無論如何,在上面的選項2和3中,我只嘗試將'deepScript'的stdout發送到'__process',並在上面複製了時髦的結果。在現實生活中,'__process'在輸出上執行一些'sed'操作,根據某些模式的存在進行一些日誌記錄。看起來''讀''等待一個'\ n'我必須找到一個解決方法。 – 2014-09-29 06:35:27