I have an infinite while loop that I only want to break out if the user press Ctrl-C.
But inside my while loop there are two counters whose value I want to print 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 the while loop and the script too. This means that the last 2 echo messages are not printed.
Is there a way that if I press Ctrl + C, I will only exit the while loop, but the rest of the script is still working?
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 using 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
source
share