Skip to content

Commit 72a2504

Browse files
authored
Modified break and continue statement (bobbyiliev#44)
1 parent 9007c06 commit 72a2504

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

ebook/en/content/011-bash-loops.md

+74
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,78 @@ done
121121
As with other languages, you can use `continue` and `break` with your bash scripts as well:
122122

123123
* `continue` tells your bash script to stop the current iteration of the loop and start the next iteration.
124+
125+
The syntax of the continue statement is as follows:
126+
127+
```bash
128+
continue [n]
129+
```
130+
131+
The [n] argument is optional and can be greater than or equal to 1. When [n] is given, the n-th enclosing loop is resumed. continue 1 is equivalent to continue.
132+
133+
```bash
134+
#!/bin/bash
135+
136+
for i in 1 2 3 4 5
137+
do
138+
if [ $i –eq 2 ]
139+
then
140+
echo “skipping number 2”
141+
continue
142+
fi
143+
echo “I is equal to $i
144+
done
145+
```
146+
147+
We can also use continue command in similar way to break command for controlling multiple loops.
148+
149+
124150
* `break` tells your bash script to end the loop straight away.
151+
152+
The syntax of the break statement takes the following form:
153+
154+
```bash
155+
break [n]
156+
```
157+
[n] is an optional argument and must be greater than or equal to 1. When [n] is provided, the n-th enclosing loop is exited. break 1 is equivalent to break.
158+
159+
Example:
160+
161+
```bash
162+
#!/bin/bash
163+
164+
num=1
165+
while [ $num –lt 10 ]
166+
do
167+
if [ $num –eq 5 ]
168+
then
169+
break
170+
fi
171+
((num++))
172+
done
173+
echo “Loop completed”
174+
```
175+
176+
We can also use break command with multiple loops. If we want to exit out of current working loop whether inner or outer loop, we simply use break but if we are in inner loop & want to exit out of outer loop, we use break 2.
177+
178+
Example:
179+
180+
```bash
181+
#!/bin/bash
182+
183+
for (( a = 1; a < 10; a++ ))
184+
do
185+
echo “outer loop: $a
186+
for (( b = 1; b < 100; b++ ))
187+
do
188+
if [ $b –gt 5 ]
189+
then
190+
break 2
191+
fi
192+
echo “Inner loop: $b
193+
done
194+
done
195+
```
196+
197+
The bash script will begin with a=1 & will move to inner loop and when it reaches b=5, it will break the outer loop.
198+
We can use break only instead of break 2, to break inner loop & see how it affects the output.

0 commit comments

Comments
 (0)