Bash – How to exit a bash loop by keyboard input

bashforinputshell-script

I have a bash lopp as

#!/bin/bash
for (( c=0; c<=1000000; c++ ))
do  
SOME STUFF HERE
done

I interrupt the long loop by a keyboard input like Ctrl+C but Ctrl+C simply terminates the script. I am looking for an alternative to continue the current cycle and break the loop after finishing the running STUFF in the current cycle.

Best Answer

One way is to trap the Control-C signal and break out of the loop, as in:

#!/bin/bash
trap break INT
for (( c=0; c<=1000000; c++ ))
do  
SOME STUFF HERE
done
echo "I have broken out of the interminably long for loop"
trap - INT
sleep 1
echo "END."
Related Question