[英]Bash - Break out of loop with Ctrl-C but continue with script
我有一個無限的while循環,如果用戶按下Ctrl-C,我只想突破。
但是我的while循環中有2個計數器,當我退出while循環時,我想要打印出它的值。
OK_COUNT=0
NOK_COUNT=0
while :
do
RESULT=`curl -s http://${IP}${ENDPOINT} --max-time 1`
if [ $RESULT == '{"status":"UP"}' ]
then
(( OK_COUNT+=1 ))
echo "`date` :: ${ENDPOINT} is OK ! Total count is $OK_COUNT "
else
(( NOK_COUNT+=1 ))
echo "`date` :: ${ENDPOINT} is UNREACHABLE ! Total count is $NOK_COUNT"
fi
sleep 0.5
done
echo $OK_COUNT
echo $NOK_COUNT
現在,當我按下Ctrl + C時,我退出while循環並退出腳本。 這意味着最后2個echo語句不能打印出來。
有沒有辦法,如果我按Ctrl + C,我只退出while循環,但其余的腳本仍然運行?
編輯/解決方案::
添加trap
,它有效!
OK_COUNT=0
NOK_COUNT=0
trap printout SIGINT
printout() {
echo $OK_COUNT
echo $NOK_COUNT
exit
}
while :
do
RESULT=`curl -s http://${IP}${ENDPOINT} --max-time 1`
if [ $RESULT == '{"status":"UP"}' ]
then
(( OK_COUNT+=1 ))
echo "`date` :: ${ENDPOINT} is OK ! Total count is $OK_COUNT "
else
(( NOK_COUNT+=1 ))
echo "`date` :: ${ENDPOINT} is UNREACHABLE ! Total count is $NOK_COUNT"
fi
sleep 0.5
done
使用上面的代碼,當我用Ctrl + C退出代碼時,我得到了。
Wed Oct 18 18:59:13 GMT 2017 :: /cscl_etl/health is OK ! Total count is 471
Wed Oct 18 18:59:13 GMT 2017 :: /cscl_etl/health is OK ! Total count is 472
^C
5
0
#
這是確保在Ctrl + C之后運行echo語句的一種方法:
trap printout SIGINT
printout() {
echo ""
echo "Finished with count=$count"
exit
}
while :
do
((count++))
sleep 1
done
運行並按下Ctrl + C時 ,此腳本的輸出如下所示:
$ bash s.sh
^C
Finished with count=2
trap
語句捕獲Ctrl + C並執行函數printout
。 該函數可以包含您喜歡的任何語句。
或者,我們可以將循環和陷阱語句放在子shell中:
$ cat t.sh
(
trap printout SIGINT
printout() {
echo ""
echo "At end of loop: count=$count"
exit
}
while :
do
((count++))
sleep 1
done
)
echo "Finishing script"
當它運行並按下Ctrl + C時 ,輸出如下:
$ bash t.sh
^C
At end of loop: count=2
Finishing script
這個方法允許我們在子shell之后繼續使用腳本。 但請注意,在子shell退出后,子shell中所做的任何變量設置或其他環境更改都將丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.