![](/img/trans.png)
[英]How to determine if an EXIT trap is defined for a BASH subshell?
[英]How to exit a Subshell
基本上,我試圖退出一個包含循環的子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時,它只是關閉對話框,但是繼續寫入文件。
編輯:我需要能夠將變量從子外殼傳遞到父外殼。 但是,我需要繼續寫入文件並保持“ Zenity”對話框出現。 我該怎么做?
生成子外殼時,它將創建當前外殼的子進程。 這意味着,如果您在一個外殼程序中編輯變量,則該變量將不會反映在另一個外殼程序中 ,因為它們是不同的進程 。 我建議您將subshell發送到后台並使用$!
獲取其PID,然后在准備就緒時使用該PID終止子外殼。 看起來像這樣:
( # 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.