Bash - Loop with Ctrl-C, but continue with script

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 trapit 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
# 
+4
source share
1 answer

Trap statement

, echo Ctrl + C:

trap printout SIGINT
printout() {
    echo ""
    echo "Finished with count=$count"
    exit
}
while :
do
    ((count++))
    sleep 1
done

Ctrl + C script :

$ bash s.sh
^C
Finished with count=2

trap Ctrl + C printout. , .

trap :

$ 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

script . , , , , .

+4
source

Source: https://habr.com/ru/post/1687745/


All Articles