How to break out of a loop in Bash?

BashShellWhile Loop

Bash Problem Overview


I want to write a Bash script to process text, which might require a while loop.

For example, a while loop in C:

int done = 0;
while(1) {
  ...
  if(done) break;
}

I want to write a Bash script equivalent to that. But what I usually used and as all the classic examples I read have showed, is this:

while read something;
do
...
done

It offers no help about how to do while(1){} and break;, which is well defined and widely used in C, and I do not have to read data for stdin.

Could anyone help me with a Bash equivalent of the above C code?

Bash Solutions


Solution 1 - Bash

It's not that different in bash.

workdone=0
while : ; do
  ...
  if [ "$workdone" -ne 0 ]; then
      break
  fi
done

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.


There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

Solution 2 - Bash

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlulyonView Question on Stackoverflow
Solution 1 - BashchepnerView Answer on Stackoverflow
Solution 2 - BashlurkerView Answer on Stackoverflow