基本上,我试图退出包含循环的子shell。这是代码: `
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时它只是关闭对话框,但一直写入文件。
编辑:我需要能够将子shell中的变量传递给父shell。但是,我需要继续写入文件并保持Zenity对话框。我该怎么做?
答案 0 :(得分:2)
当您生成子shell时,它会创建当前shell的子进程。这意味着如果您在一个shell中编辑变量,它将不会反映在另一个shell中,因为它们是不同的进程。我建议您将子shell发送到后台并使用$!
来获取其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