2016-12-28 53 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