Bash – Terminate BASH For loop, that contains long sleep and other stuff, using any specific key

bashshell-scriptsleep

I have a bash script that

  • has a for loop that iterates a lot of times and sleeps between iterations, potentially for a long time. It then

  • writes results to a file, then terminates.

On occasion I get the result I need before many loop iterations are complete.

On these occasions I need the script to break out of the for loop while it is either

  • doing stuff, or

  • sleeping

in such as way that it will continue with the rest of the script, after the for loop, which is writing a report file of data it's gathered so far.

I wish to use a key combination, eg CTRL+Q, to break out of the for loop.

Script looks like this:

#!/bin/bash

for (( c=0; c<=$1; c++ ))
do  

# SOME STUFF HERE
#  data gathering into arrays and other commands here etc

# sleep potentially for a long time
sleep $2

done

#WRITE REPORT OUT TO SCREEN AND FILE HERE

Best Answer

I've not had contact with this kind of tasks for a while, but I remember something like this used to work:

#!/bin/bash

trap break INT

for (( c=0; c<=$1; c++ ))
do  

# SOME STUFF HERE
#  data gathering into arrays and other commands here etc

    echo loop "$c" before sleep

    # sleep potentially for a long time
    sleep "$2"

    echo loop "$c" after sleep

done

#WRITE REPORT OUT TO SCREEN AND FILE HERE

echo outside

The idea is to use Ctrl-C to break the loop. This signal (SIGINT) is caught by the trap, which breaks the loop and lets the rest of the script follow.

Example:

$ ./s 3 1
loop 0 before sleep
loop 0 after sleep
loop 1 before sleep
^Coutside

Let me know if you have any problems with this.

Related Question