270

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?

3 Answers 3

361

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.

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

1 Comment

also note: depending on how complex the work that is done, you may also use && break or || break depending on the expected return value
99
while true ; do
    ...
    if [ something ]; then
        break
    fi
done

1 Comment

I think this is the most straight forward way to do it, to only difference that I would do is to use double brackets like [[ something if complex ]] thats all.
-3
read -p "Hey dear user, let's play a game, : " answer
int done = 0
while [[ $answer != "yes" ]]; do

    read -p "guess a number from 10 to 100 : " answer

    if [[  $answer == 70 ]]; then

        echo "Congratulations! You guessed the number."

    elif [[  $answern -lt 70 ]]; then

        echo " dear user, u too close"

    elif [[  $answer -gt 70 ]]; then

        echo " u are to far, dear user"

    if (done); break

    fi
 
done

1 Comment

You might want to give this another try, because neither the logic nor the syntax of that last if checks out. (done is never set, if (done) is a weird way to check for it being set, and the if is inside the last elif.) Also, I don't feel it adds anything to the answers already given.

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.