Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of a loop in Bash?

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?

like image 288
lulyon Avatar asked Aug 28 '13 12:08

lulyon


People also ask

How do you break a loop in bash?

Use the break statement to exit a while loop when a particular condition realizes. The following script uses a break inside a while loop: #!/bin/bash i=0 while [[ $i -lt 11 ]] do if [[ "$i" == '2' ]] then echo "Number $i!" break fi echo $i ((i++)) done echo "Done!"

How do you get out of a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How do you break out of a loop in shell?

break exits from a for, select, while, or until loop in a shell script. If number is given, break exits from the given number of enclosing loops. The default value of number is 1 . break is a special built-in shell command.

How do you exit a while loop in Linux?

The while loop above will run indefinitely. You can terminate the loop by pressing CTRL+C .


1 Answers

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.

like image 139
chepner Avatar answered Oct 07 '22 05:10

chepner