Skip to content

Modified break and continue statement #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 29, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions ebook/en/content/011-bash-loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,78 @@ done
As with other languages, you can use `continue` and `break` with your bash scripts as well:

* `continue` tells your bash script to stop the current iteration of the loop and start the next iteration.

The syntax of the continue statement is as follows:

```bash
continue [n]
```

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.

```bash
#!/bin/bash

for i in 1 2 3 4 5
do
if [ $i –eq 2 ]
then
echo “skipping number 2”
continue
fi
echo “I is equal to $i”
done
```

We can also use continue command in similar way to break command for controlling multiple loops.


* `break` tells your bash script to end the loop straight away.

The syntax of the break statement takes the following form:

```bash
break [n]
```
[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.

Example:

```bash
#!/bin/bash

num=1
while [ $num –lt 10 ]
do
if [ $num –eq 5 ]
then
break
fi
((num++))
done
echo “Loop completed”
```

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.

Example:

```bash
#!/bin/bash

for (( a = 1; a < 10; a++ ))
do
echo “outer loop: $a”
for (( b = 1; b < 100; b++ ))
do
if [ $b –gt 5 ]
then
break 2
fi
echo “Inner loop: $b ”
done
done
```

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.
We can use break only instead of break 2, to break inner loop & see how it affects the output.