6

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.

1 Answer 1

5

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."

For more detail of how this works, the key lines being:

trap break INT

and also

trap - INT

We use "break" to tell trap we want to run break to break the loop when INT (interrupt, aka SIGINT) signal is generated (which happens when press Ctrl+C)

Instead of "break" we could put arbitrary shell commands in quotes, and that will be executed when the given signal (INT in our case) is generated.

Lastly we run trap again with - to restore the "INT" handler to the default action.

Here are some more resources for further reading and examples:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .