I have an infinite while loop that I only want to break out of if the user presses Ctrl - C.
But there are 2 counters inside my while loop whose value I want printed out when I exit the while loop.
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
Now when I press Ctrl + C, I exit out of the while loop and out of the script too. This means the last 2 echo statements dont get to be printed.
Is there a way that if I press Ctrl + C, I only exit out of the while loop but the rest of the script still runs ?
EDIT/SOLUTION ::
After adding trap, It works !
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
With the above code, when I exit the code with Ctrl + C, I get.
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
#