Linux bash do continue

Bash Break and Continue

When the ‘break’ command is executed, the loop is terminated immediately, and the script continues to execute the next line of code after the loop. When the ‘continue’ command is executed, the script skips the rest of the code in the current iteration and moves on to the next loop iteration.

This article is about the break and continue statements in Bash, which you can use, and this guide includes the following.

  • How to Use a break in Bash?
  • Example 1: Guess Game
  • Example 2: Print a Series of Numbers
  • How to Use a continue in Bash?
  • Example 1: Printing the Specific Output (with numbers)
  • Example 2: Skipping a Number in the Loop

Now let’s get on with it as we explain the above.

How to Use a break in Bash?

The break statement is used to exit from a loop based on a specific condition, and here’s how you can use it in your scripts.

1. for, while, or until loop 2. do 3. command-one 4. command-two 5. if [ some condition ]; then 6. break 7. fi 8. command-three 9. done

Here’s the breakdown of the above syntax.

Lines 1, 2 & 9 are part of the loop that you’d use.

Lines 3, 4 & 8 have the conditions.

Lines 5 & 7 are a part of the ‘if statement.’

Line 6 has the break statement to exit the loop.

Now you’ll understand it clearly by following these examples.

Example 1: Guess Game

In this example, we’ve created a script where the user has to guess the favorite number between 1 and 10, and the user will be given a total of 5 tries. If you’ve guessed correctly or the number of attempts exceeds 5, the loop will exit using the break statement. Here’s the script.

#!/bin/bash numSelect=`shuf -i 0-10 -num` echo "You have 5 tries to guess my favorite number between 0 and 10" for ((try=1; try

The script is named “GuessGame.sh” which is executed using this command.

When the script finds the randomly generated and the user enters the same number, it will execute the break statement to exit the loop, and the message “You guessed my favorite number $num” is printed.

Example 2: Print a Series of Numbers

In this example, there’s a script that prints a series of numbers, but when it comes to the number ‘5’ the break statement will be executed, and the loop will exit, displaying a message. Here’s the script.

#!/bin/bash count=1 while [ $count -le 10 ] do printf "The current value of count is $count\n" ((count++)) if [ $count -eq 5 ] then printf "Count has a value of $count\n" printf "The count has reached 5, now the break statement will be executed\n" break fi done

This script is named ‘PrintNum.sh’, and we’ll execute it using this command.

The above script, in simple words, is supposed to print the numbers from one to ten along with the text, but it’ll only go to five and then exit because there’s a condition that executes the break statement once matched.

How to Use a continue in Bash?

The continue statement works so that, unlike the break, it doesn’t exit the loop when a specific condition is met; instead, it returns to the top of the continue statement. The continue syntax is similar to the break statement, which is as follows:

for, while, or until loop do command-one command-two if [ some condition ]; then continue fi command-three done command-four

After going through the below, you’ll understand it more clearly.

Example 1: Printing the Specific Output (With Numbers)

In this example, a script is created that prints the numbers from one to ten but at nine (we’ve set that condition), it’ll also print a text along with it. Here’s the script of it.

#!/bin/bash for num in do if [[ $num == '9' ]] then echo "Number $num" continue fi echo "$num" done echo "All numbers are printed, and one of them is highlighted with text"

It is named ‘conEX.sh” and to execute this; the following command is used.

As seen in the above image, all the numbers between 1 and 10 are printed but see what is there on number 9, and if we used the break statement, then there’d be nothing printed after 10.

Example 2: Skipping a Number in the Loop

In this example, a range of numbers (1-10) is printed while skipping the numbers, let’s say ‘2 & 9’; here’s the script.

#!/bin/bash num=0 while [ $num -lt 10 ] do (( num++ )) [ $num -eq 2 -o $num -eq 9 ] && continue echo "$num" done

It is named ‘skipNum.sh’, and the following command is used to execute this script.

The above image shows that the numbers (2 & 9) are skipped while others are printed, and you can do almost anything that a Linux can do through scripts, and all you need to do is learn.

Conclusion

Controlling the flow of your script is required as everything will be executed, which could temper the output and completely change the results. This guide elaborates on the syntax and a few examples to help you understand the break and continue statements in bash.

Источник

Операторы 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 используется для выхода из текущей итерации цикла и начала следующей итерации.

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

Источник

Команды break и continue. Оболочка Bash. Linux.

Главное меню » Команды break и continue. Оболочка Bash. Linux.

Linux. Оболочка Bash. Команды break и continue

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

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

Команда break в Bash

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

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

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

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

i=0 while [[ $i -lt 5 ]] do echo "Номер: $i" ((i++)) if [[ $i -eq 2 ]]; then break fi done echo 'Все Сделано!'
Номер: 0 Номер: 1 Все Сделано!

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

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

for i in ; do for j in ; do if [[ $j -eq 2 ]]; then break fi echo "j: $j" done echo "i: $i" done echo 'Все Сделано!'
j: 1 i: 1 j: 1 i: 2 j: 1 i: 3 Все Сделано!

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

for i in ; do for j in ; do if [[ $j -eq 2 ]]; then break 2 fi echo "j: $j" done echo "i: $i" done echo 'Все Сделано!'

Команда continue в Bash

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

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

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

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

i=0 while [[ $i -lt 5 ]]; do ((i++)) if [[ "$i" == '2' ]]; then continue fi echo "Номер: $i" done echo 'Все Сделано!'
Номер: 1 Номер: 3 Номер: 4 Номер: 5 Все Сделано!

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

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

for i in ; do if [[ $(( $i % 9 )) -ne 0 ]]; then continue fi echo "Делится на 9: $i" done
Делится на 9: 9 Делится на 9: 18 Делится на 9: 27 Делится на 9: 36 Делится на 9: 45

Вывод

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

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

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

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Читайте также:  Общая папка пользователей astra linux
Оцените статью
Adblock
detector