title: Bash - Break out of loop with Ctrl-C but continue with script
body: <p>I have an infinite while loop that I only want to break out of if the user presses Ctrl - C.</p>
  
  <p>But there are 2 counters inside my while loop whose value I want printed out when I exit the while loop.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>
  
  <p>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 ? </p>
  
  <p><strong>EDIT/SOLUTION ::</strong></p>
  
  <p>After adding <code>trap</code>, It works !</p>
  
  <pre><code>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
  </code></pre>
  
  <p>With the above code, when I exit the code with Ctrl + C, I get.</p>
  
  <pre><code>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
  # 
  </code></pre>