1

I'm running an infinite while loop in bash that has a counting element to it.

while :
do
    #stuff including counting
    trap break int
done

This works as I would like for the most part. When I hit Ctrl+C, the loop stops, but the script continues. However, the loop stops in the middle of the loop which means that the final count is inaccurate.

Is there a way to make this loop break at the very end?

1
  • If one of the answers here resolved your question please accept that answer. Accepting an answer closes this questions and rewards the author of the accepted answer. If your question was not resolved consider explaining why. Commented Feb 15, 2019 at 12:03

1 Answer 1

4

Instead of executing break you can set a flag and break the loop at a designated location when the flag is set. Note that in a loop the loop head can also be seen as the very end of the loop.

state=run
trap 'state=end' int
while [ "$state" = run ]
do
    # stuff
done

If you want to break somewhere in the middle use

state=run
trap 'state=end' int
while :
do
    # stuff
    [ "$state" = end ] && break
    # more stuff
done

You can test the behavior quiet nicely by replacing # stuff with for i in {1..20}; do printf .; sleep 0.1; done; echo:

Script in action

As we can see in the clip above, the outer loop finishes its current iteration (# stuff) until the very end.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.