2016-12-28 52 views
0

基本上,我試圖退出包含循環的子殼。這裏是代碼: `如何退出子殼

stop=0 
( # subshell start 
    while true   # Loop start 
    do 
     sleep 1   # Wait a second 
     echo 1 >> /tmp/output   # Add a line to a test file 

     if [ $stop = 1 ]; then exit; fi   # This should exit the subshell if $stop is 1 
    done # Loop done 

) |   # Do I need this pipe? 

    while true 
    do 
     zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew  # This opens Zenity and shows the file. It returns 0 when I click stop. 

     if [ "$?" = 0 ]  # If Zenity returns 0, then 
     then 
     let stop=1  # This should close the subshell, and 
     break  # This should close this loop 
     fi 
    done  # This loop end 
    echo Done 

這是行不通的。它從不說完成。當我按下Stop時,它只是關閉對話框,但一直寫入文件。

編輯:我需要能夠將一個變量從subshel​​l傳遞到父shell。但是,我需要繼續寫入文件並保持Zenity對話框出現。我將如何做到這一點?

+0

我不認爲我理解。有退出子殼體的特殊方法嗎? – Feldspar15523

回答

2

當你產生一個子shell時,它會創建一個當前shell的子進程。這意味着如果你在一個shell中編輯一個變量,它將不會被反映到另一個shell中,因爲它們是不同的進程。我建議你將subshel​​l發送到後臺並使用$!來獲得它的PID,然後在你準備好時使用該PID來殺死子shell。這看起來像這樣:

(        # subshell start 
    while true     # Loop start 
    do 
     sleep 1     # Wait a second 
     echo 1 >> /tmp/output # Add a line to a test file 
    done      # Loop done 

) &        # Send the subshell to the background 

SUBSHELL_PID=$!     # Get the PID of the backgrounded subshell 

while true 
do 
    zenity --title="Test" --ok-label="Stop" --cancel-label="Refresh" --text-info --filename=/tmp/output --font=couriernew  # This opens Zenity and shows the file. It returns 0 when I click stop. 

    if [ "$?" = 0 ]    # If Zenity returns 0, then 
    then 
    kill $SUBSHELL_PID   # This will kill the subshell 
    break      # This should close this loop 
    fi 
done       # This loop end 

echo Done 
+0

帶括號的顯式子shell是無用的(可能不需要)。 –

+0

它可以使用或不使用括號;這只是將subshel​​l發送到後臺或循環的問題。我個人比較喜歡subshel​​l,因爲它清楚地告訴了什麼被髮送到了後臺,而不是'while while ......... done&',這對我來說看起來像'done'是背景(儘管它仍然有效)。是否有任何令人信服的理由來省略這些parens? –

+0

如果我在子shell中更改一個變量,那麼它會在主變更嗎?如果沒有,那我該如何在兩者之間發送價值? – Feldspar15523