Break linux for loop

Операторы break и continue в Bash

Циклы позволяют выполнять одну или несколько команд несколько раз, пока не будет выполнено определенное условие. Однако иногда вам может потребоваться изменить ход цикла и завершить цикл или только текущую итерацию.

В Bash операторы break и continue позволяют контролировать выполнение цикла.

Оператор break в Bash

Оператор break завершает текущий цикл и передает управление программой команде, которая следует за завершенным циклом. Он используется для выхода из цикла for , while , until или select . s Синтаксис оператора break имеет следующий вид:

[n] — необязательный аргумент и должен быть больше или равен 1. Если задано [n] , завершается n-ый включающий цикл. break 1 эквивалентен break .

Чтобы лучше понять, как использовать оператор break , давайте взглянем на следующие примеры.

В приведенном ниже сценарии, исполнение в while цикла будет прерван после того , как текущая итерация элемент равен 2 :

i=0 while [[ $i -lt 5 ]] do echo "Number: $i" ((i++)) if [[ $i -eq 2 ]]; then break fi done echo 'All Done!' 
Number: 0 Number: 1 All Done! 

Вот пример использования оператора break внутри вложенных циклов for .

Если аргумент [n] не указан, break завершает самый внутренний охватывающий цикл. Внешние циклы не завершаются:

for i in 1..3>; do for j in 1..3>; do if [[ $j -eq 2 ]]; then break fi echo "j: $j" done echo "i: $i" done echo 'All Done!' 
j: 1 i: 1 j: 1 i: 2 j: 1 i: 3 All Done! 

Если вы хотите выйти из внешнего цикла, используйте break 2 . Аргумент 2 сообщает break чтобы завершить второй охватывающий цикл:

for i in 1..3>; do for j in 1..3>; do if [[ $j -eq 2 ]]; then break 2 fi echo "j: $j" done echo "i: $i" done echo 'All Done!' 

Оператор continue в Bash

Оператор continue пропускает оставшиеся команды внутри тела охватывающего цикла для текущей итерации и передает управление программой следующей итерации цикла.

Синтаксис оператора continue следующий:

Аргумент [n] является необязательным и может быть больше или равен 1. Когда задано [n] , возобновляется n-й включающий цикл. continue 1 эквивалентно continue .

В приведенном ниже примере, когда текущий повторяемый элемент равен 2 , оператор continue приведет к возврату выполнения к началу цикла и продолжению следующей итерации.

i=0 while [[ $i -lt 5 ]]; do ((i++)) if [[ "$i" == '2' ]]; then continue fi echo "Number: $i" done echo 'All Done!' 
Number: 1 Number: 3 Number: 4 Number: 5 All Done! 

Следующий скрипт печатает числа от 1 до 50 , которые делятся на 9 .

Если число не делится на 9 , оператор continue пропускает команду echo и передает управление следующей итерации цикла.

for i in 1..50>; do if [[ $(( $i % 9 )) -ne 0 ]]; then continue fi echo "Divisible by 9: $i" done 
Divisible by 9: 9 Divisible by 9: 18 Divisible by 9: 27 Divisible by 9: 36 Divisible by 9: 45 

Выводы

Циклы — одна из фундаментальных концепций языков программирования. В языках сценариев, таких как Bash, циклы полезны для автоматизации повторяющихся задач.

Оператор break используется для выхода из текущего цикла. Оператор continue используется для выхода из текущей итерации цикла и начала следующей итерации.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Unix / Linux — Shell Loop Control

In this chapter, we will discuss shell loop control in Unix. So far you have looked at creating loops and working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of the loop.

In this chapter, we will learn following two statements that are used to control shell loops−

The infinite Loop

All the loops have a limited life and they come out once the condition is false or true depending on the loop.

A loop may continue forever if the required condition is not met. A loop that executes forever without terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.

Example

Here is a simple example that uses the while loop to display the numbers zero to nine −

#!/bin/sh a=10 until [ $a -lt 10 ] do echo $a a=`expr $a + 1` done

This loop continues forever because a is always greater than or equal to 10 and it is never less than 10.

The break Statement

The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then steps down to the code following the end of the loop.

Syntax

The following break statement is used to come out of a loop −

The break command can also be used to exit from a nested loop using this format −

Here n specifies the n th enclosing loop to the exit from.

Example

Here is a simple example which shows that loop terminates as soon as a becomes 5 −

#!/bin/sh a=0 while [ $a -lt 10 ] do echo $a if [ $a -eq 5 ] then break fi a=`expr $a + 1` done

Upon execution, you will receive the following result −

Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and var2 equals 0

#!/bin/sh for var1 in 1 2 3 do for var2 in 0 5 do if [ $var1 -eq 2 -a $var2 -eq 0 ] then break 2 else echo "$var1 $var2" fi done done

Upon execution, you will receive the following result. In the inner loop, you have a break command with the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately from the inner loop as well.

The continue statement

The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop.

This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop.

Syntax

Like with the break statement, an integer argument can be given to the continue command to skip commands from nested loops.

Here n specifies the n th enclosing loop to continue from.

Example

The following loop makes use of the continue statement which returns from the continue statement and starts processing the next statement −

#!/bin/sh NUMS="1 2 3 4 5 6 7" for NUM in $NUMS do Q=`expr $NUM % 2` if [ $Q -eq 0 ] then echo "Number is an even number!!" continue fi echo "Found odd number" done

Upon execution, you will receive the following result −

Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number

Источник

Bash break How to Exit From a Loop

If you are a Linux or Unix user, then you might be familiar with Bash shell. Bash is a popular command-line interpreter that is widely used in Linux, macOS, and other Unix-like operating systems. It is a powerful tool for running scripts, automating tasks, and working with command line. One of most common use cases for Bash is working with loops, which allow you to repeat a set of instructions multiple times. However, sometimes you might need to break out of a loop before it has finished executing. In this article, we will explore how to exit from a loop in Bash.

What is a Loop in Bash?

Before we dive into how to exit from a loop, let’s first understand what a loop is in Bash. A loop is a programming construct that allows you to execute a set of instructions repeatedly. In Bash, there are two types of loops −

for loop

A for loop is used to iterate over a sequence of values, such as a range of numbers or a list of strings.

while loop

A while loop is used to execute a set of instructions repeatedly as long as a certain condition is true.

Both types of loops can be useful for automating tasks, but they can also cause your script to get stuck in an infinite loop if you’re not careful. Therefore, it’s important to know how to exit from a loop if you need to.

How to Exit from a Loop in Bash?

To exit from a loop in Bash, you can use break statement. break statement is a control statement that allows you to terminate a loop prematurely. When break statement is encountered inside a loop, loop is immediately terminated, and program continues executing instructions that follow loop.

The syntax for break statement in Bash is as follows −

To use break statement, you simply include it inside loop where you want to exit. Here’s an example of how to use break statement in a for loop −

for i in do echo $i if [ $i -eq 5 ] then break fi done

In this example, we are using a for loop to iterate over values from 1 to 10. Inside loop, we are using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 5. If it is, then we use break statement to exit loop. As a result, when program is run, it will print values 1 through 5, and then terminate loop.

Similarly, you can use break statement in a while loop. Here’s an example −

i=1 while [ $i -le 10 ] do echo $i if [ $i -eq 5 ] then break fi i=$((i+1)) done

In this example, we are using a while loop to print values from 1 to 10. Inside loop, we are using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 5. If it is, then we use break statement to exit loop. As a result, when program is run, it will print values 1 through 5, and then terminate loop.

Tips for Using Break Statement

While break statement is a powerful tool for exiting from a loop, it’s important to use it carefully. Here are a few tips to keep in mind −

Always use break statement inside an if statement: To avoid accidentally exiting from a loop prematurely, it’s a good practice to always use break statement inside an if statement that checks for a specific condition. This way, you can ensure that loop will only exit when you want it to.

Use descriptive variable names: When using a loop, it’s important to use descriptive variable names that make it clear what loop is doing. This can help you avoid confusion and make it easier to debug your code if something goes wrong.

Test your code: Before running your code in a production environment, it’s a good idea to test it in a development or testing environment first. This can help you catch any errors or issues before they cause problems in a live environment.

Use comments to explain your code: To make your code more readable and understandable, it’s a good idea to use comments to explain what your code is doing. This can be especially helpful if you’re working on a complex script that involves multiple loops and conditional statements.

Examples of Using Break Statement

Let’s take a look at a few more examples of using break statement in Bash.

Example 1: Exiting a Loop Based on User Input

In this example, we will create a script that asks user to input a number. script will then use a while loop to count up to that number, but will exit loop if user enters number 0.

#!/bin/bash echo "Enter a number: " read number i=1 while [ $i -le $number ] do echo $i if [ $i -eq 0 ] then break fi i=$((i+1)) done echo "Done"

In this script, we are using read command to prompt user to input a number. We then use a while loop to count up to that number, using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 0. If it is, then we use break statement to exit loop. As a result, loop will terminate if user enters 0, and script will print «Done» when it is finished.

Example 2: Using a for Loop with Break Statement

In this example, we will use a for loop to iterate over a list of names. We will use break statement to exit loop when we find a specific name.

#!/bin/bash names=("John" "Jane" "Bob" "Sarah") for name in $ do echo $name if [ $name = "Bob" ] then break fi done echo "Done"

In this script, we are using a for loop to iterate over values in names array. Inside loop, we are using echo command to print value of variable name. We also have an if statement that checks if value of name is equal to «Bob». If it is, then we use break statement to exit loop. As a result, loop will terminate when it finds name «Bob», and script will print «Done» when it is finished.

Conclusion

In conclusion, break statement is a powerful tool for exiting from a loop in Bash. By using break statement inside an if statement that checks for a specific condition, you can ensure that your script will only exit loop when you want it to. Whether you are working with a for loop or a while loop, break statement can help you automate tasks and make your code more efficient. With careful planning and testing, you can use break statement to create robust and reliable Bash scripts that can handle a wide range of tasks. Remember to use descriptive variable names, comments, and testing to ensure that your code is easy to understand and maintain. With these tips and examples, you should now be able to use break statement in your own Bash scripts to exit from loops and improve your workflow.

Источник

Читайте также:  Wireguard настройка client linux
Оцените статью
Adblock
detector