6 bash
我有一个无限的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
Run Code Online (Sandbox Code Playgroud)
现在,当我按下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
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,当我用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
#
Run Code Online (Sandbox Code Playgroud)
这是确保在Ctrl+ 之后运行echo语句的一种方法C:
trap printout SIGINT
printout() {
echo ""
echo "Finished with count=$count"
exit
}
while :
do
((count++))
sleep 1
done
Run Code Online (Sandbox Code Playgroud)
当运行并且按下Ctrl+时C,此脚本的输出如下所示:
$ bash s.sh
^C
Finished with count=2
Run Code Online (Sandbox Code Playgroud)
该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"
Run Code Online (Sandbox Code Playgroud)
当它运行并且按下Ctrl+时C,输出如下:
$ bash t.sh
^C
At end of loop: count=2
Finishing script
Run Code Online (Sandbox Code Playgroud)
这个方法允许我们在子shell之后继续使用脚本.但请注意,子shell退出后,子shell中所做的任何变量设置或其他环境更改都将丢失.