- Глава 10. Циклы и ветвления
- 10.1. Циклы
- Bash While Loop Examples
- bash while loop syntax
- Redirecting user input for a while Loop
- How do I use while as infinite loops ?
- Conditional while loop exit with break statement
- Early continuation with the continue statement
- Recommended readings
- Bash цикл While
- Bash while Loop
- Это руководство охватывает основы while циклов в Bash. Мы также покажем вам , как использовать break и continue заявление , чтобы изменить поток цикла.
- Цикл While
- Бесконечный while цикл
- Читать файл построчно
- Операторы break и continue
- break
- continue
- Вывод
Глава 10. Циклы и ветвления
Управление ходом исполнения — один из ключевых моментов структурной организации сценариев на языке командной оболочки. Циклы и преходы являются теми инструментальными средствами, которые обеспечивают управление порядком исполнения команд.
10.1. Циклы
Цикл — это блок команд, который исполняется многократно до тех пор, пока не будет выполнено условие выхода из цикла.
циклы for
Это одна из основных разновидностей циклов. И она значительно отличается от аналога в языке C.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | BASH or KSH on Linux/Unix-like systems |
Est. reading time | 1 minute |
bash while loop syntax
The syntax is as follows:
command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. Here is the while loop one-liner syntax:
For example following while loop will print welcome 5 times on screen:
And here is above code as a bash while one liner:
x=1; while [ $x -le 5 ]; do echo «Welcome $x times» $(( x++ )); done
Here is a sample shell code to calculate factorial using while loop:
To run just type:
$ chmod +x script.sh
$ ./script.sh 5
The while loop in action on my Ubuntu Linux desktop
You can easily evaluate the options passed on the command line for a script using while loop:
Redirecting user input for a while Loop
How about reading user input from a file? Say you have a file as follows with various IP address:
cat bad-guys.ips.txt
List of crackers IP address:
Here is a bash while loop that read those IP address separated by Internal Field Separator ( $IFS ) to an octothorpe ( # ):
Click to enlarge
How do I use while as infinite loops ?
Infinite for while can be created with empty expressions, such as:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Conditional while loop exit with break statement
You can do early exit with the break statement inside the whil loop. You can exit from within a WHILE using break. General break statement inside the while loop is as follows:
In this example, the break statement will skip the while loop when user enters -1, otherwise it will keep adding two numbers:
Early continuation with the continue statement
To resume the next iteration of the enclosing WHILE loop use the continue statement as follows:
Recommended readings
We learned that bash while loop executes while a condition is true. See the following resource
- See all sample shell script in our bash shell directory
- Bash loops from our Linux shell scripting tutorial guide
- man bash
- help while
- help <
- help break
- help continue
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Nice to see the Bash shell,
How do you break out of a loop
is there a break statement, or do you have to use a goto?
Yes there is a break and continue statement. man bash has more information.
Very useful examples, thank you!
Thank you so much .
you define very nicly all exampls regarding while loop secquence
statement….
could u please give the shell script for printing the fibonocci series and to know if the number is palindrome and also if it an armstrong number
Does anyone know how to write a script that echoes three different arguments three times using a loop
shift command to traverse through arguments
does anyone can give an example of a while loop within a loop?
The script “test” should set variable “filter_mode” to FALSE if there are no lines in the file “switches” and to TRUE if there exists at least one line in the file “switches”.
Why do I get “filter_mode : FALSE” eventually?
$ cat test
And my script:
Run as:
gg@GeorgSimon:
$ cat switches
switch
gg@GeorgSimon:
$ sh test
switch : switch
filter_mode : TRUE
filter_mode : FALSE
how to write a program in bash for displaying table using until statement? table should be like
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
plz reply soon….thanks
Источник
Bash цикл While
Bash while Loop
Это руководство охватывает основы while циклов в Bash. Мы также покажем вам , как использовать break и continue заявление , чтобы изменить поток цикла.
Циклы являются одним из фундаментальных понятий языков программирования. Циклы удобны, когда вы хотите выполнить серию команд несколько раз, пока не будет выполнено определенное условие.
В языках сценариев, таких как Bash, циклы полезны для автоматизации повторяющихся задач. В скриптах Bash есть три основных конструкции циклов: for , while и until .
Цикл While
while Цикл используется для выполняет заданный набор команд неизвестное число раз до тех пор , как данное условие принимает значение истинно.
Цикл Bash while принимает следующую форму:
Обявление начинается с while ключевого слова, за которым следует условное выражение.
Условие оценивается перед выполнением команд. Если условие оценивается как true, команды выполняются. В противном случае, если условие оценивается как ложное, цикл прерывается, и управление программой передается следующей команде.
В приведенном ниже примере на каждой итерации текущее значение переменной i печатается и увеличивается на единицу.
Бесконечный while цикл
Бесконечный цикл — это цикл, который повторяется бесконечно и никогда не заканчивается. Если условие всегда оценивается как истинное, вы получаете бесконечный цикл.
В следующем примере мы используем встроенную команду : для создания бесконечного цикла. : всегда возвращает истину. Вы также можете использовать true встроенный или любой другой оператор, который всегда возвращает true.
while Цикл выше , будет работать бесконечно. Вы можете завершить цикл, нажав CTRL+C .
Вот однострочный эквивалент:
Читать файл построчно
Одним из наиболее распространенных применений while цикла является построчное чтение файла, потока данных или переменной.
Вот пример, который читает /etc/passwd файл построчно и печатает каждую строку:
Вместо того, чтобы управлять while циклом с условием, мы используем входную redirection ( ), чтобы передать файл read команде, которая управляет циклом. while Цикл будет выполняться до тех пор , последняя строка не читается.
При чтении файла построчно, всегда используйте read с -r возможностью предотвращения обратного слэша выступать в качестве экранирующего символа.
По умолчанию read команда обрезает начальные / конечные пробельные символы (пробелы и символы табуляции). Используйте IFS= опцию прежде, read чтобы предотвратить это поведение:
Операторы break и continue
break И continue заявления могут быть использованы для управления выполнением цикла While.
break
break Оператор завершает текущий цикл и передает управление программой к команде, следующей за прерванный цикл. Обычно используется для завершения цикла при выполнении определенного условия.
В следующем примере выполнение цикла будет прервано, как только текущий повторяющийся элемент будет равен 2
continue
continue Оператор завершает текущую итерацию цикла и передает управление программой к следующей итерации цикла.
В следующем ниже, после того , как текущий итерированным элемент равен 2 по continue исполнению заявления заставит вернуться к началу цикла и продолжить со следующей итерации.
Вывод
while Цикл многократно выполняет заданный набор команд до тех пор , как условие истинно.
Источник