- Цикл while в Bash
- while цикл
- Бесконечный цикл while
- Прочитать файл построчно
- break и continue
- break
- continue
- Выводы
- While loop
- Contents
- The while loop syntax
- while loop Example
- Using ((expression)) Format With The While Loop
- Reading A Text File With Separate Fields
- 7. Loops
- For Loops
- While Loops
- 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
Цикл while в Bash
Циклы — одна из фундаментальных концепций языков программирования. Циклы удобны, когда вы хотите выполнить серию команд несколько раз, пока не будет выполнено определенное условие.
В языках сценариев, таких как Bash, циклы полезны для автоматизации повторяющихся задач. В Bash сценариях доступны такие циклы как for, while, и until.
В этом руководстве рассматриваются основы циклов while в Bash. Мы также покажем вам, как использовать операторы break и continue чтобы изменить ход цикла.
while цикл
В while цикл используется для выполняет заданный набор команд неизвестное число раз до тех пор , как данное условие принимает значение истинно.
Цикл while Bash имеет следующую форму:
Оператор while начинается с ключевого слова while , за которым следует условное выражение.
Условие оценивается перед выполнением команд. Если условие истинно, команды выполняются. В противном случае, если условие оценивается как ложное, цикл завершается, и управление программой будет передано следующей команде.
В приведенном ниже примере на каждой итерации текущее значение переменной i печатается и увеличивается на единицу.
Цикл вторника повторяется до тех пор, пока i меньше или равно двум. Он выдаст следующий результат:
Бесконечный цикл while
Бесконечный цикл — это цикл, который повторяется бесконечно и никогда не завершается. Если условие всегда истинно, вы получаете бесконечный цикл.
В следующем примере мы используем встроенную команду : для создания бесконечного цикла. : всегда возвращает истину. Вы также можете использовать true встроенный или любой другой оператор, который всегда возвращает true.
В while цикл выше будет работать до бесконечности. Вы можете прервать цикл, нажав CTRL+C
Вот однострочный эквивалент:
Прочитать файл построчно
Одним из наиболее распространенных использований в while петли , чтобы прочитать файл, поток данных или переменной построчно.
Вот пример, который считывает файл /etc/passwd построчно и печатает каждую строку:
Вместо того , чтобы контролировать while цикл с условием, что мы используем перенаправления ввода ( ) , чтобы передать файл на read команды, которая контролирует цикл. В while цикл будет выполняться до тех пор , последняя строка не читается.
При чтении файла построчно всегда используйте read с опцией -r чтобы обратная косая черта не использовалась как escape-символ.
По умолчанию команда read обрезает начальные / конечные пробельные символы (пробелы и табуляции). Используйте параметр IFS= перед read чтобы предотвратить такое поведение:
break и continue
Операторы break и continue могут использоваться для управления выполнением цикла while.
break
Оператор break завершает текущий цикл и передает управление программой команде, которая следует за завершенным циклом. Обычно он используется для завершения цикла при выполнении определенного условия.
В следующем примере выполнение цикла будет прервано, когда текущий повторяемый элемент станет равным 2 .
continue
Оператор continue завершает текущую итерацию цикла и передает управление программой следующей итерации цикла.
В нижеследующем ниже, как только текущий повторяемый элемент равен 2 оператор continue заставит выполнение вернуться к началу цикла и продолжить следующую итерацию.
Выводы
В while цикл многократно выполняет заданный набор команд до тех пор , как условие истинно.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
While loop
The while statement is used to execute a list of commands repeatedly.
Contents
The while loop syntax
Command1..commandN will execute while a condition is true. To read a text file line-by-line, use the following syntax:
IFS is used to set field separator (default is while space). The -r option to read command disables backslash escaping (e.g., \n, \t). This is failsafe while read loop for reading text files.
while loop Example
Create a shell script called while.sh:
Save and close the file. Run it as follows:
The script initializes the variable n to 1, and then increments it by one. The while loop prints out the «Welcome $n times» until it equals 5 and exit the loop.
Using ((expression)) Format With The While Loop
You can use ((expression)) syntax to test arithmetic evaluation (condition). If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. To replace while loop condition while [ $n -le 5 ] with while (( num Reading A Text File
You can read a text file using read command and while loop as follows (whilereadfile.sh):
Save and close the file. Run it as follows:
Reading A Text File With Separate Fields
You can store above output in two separate fields as follows (whilereadfields.sh):
Run it as follows:
Another useful example for reading and phrasing /etc/passwd file using the while loop (readpasswd.sh):
Save and close the file. Run it as follows:
Источник
7. Loops
Most languages have the concept of loops: If we want to repeat a task twenty times, we don’t want to have to type in the code twenty times, with maybe a slight change each time.
As a result, we have for and while loops in the Bourne shell. This is somewhat fewer features than other languages, but nobody claimed that shell programming has the power of C.
For Loops
for loops iterate through a set of values until the list is exhausted:
Try this code and see what it does. Note that the values can be anything at all:
This is well worth trying. Make sure that you understand what is happening here. Try it without the * and grasp the idea, then re-read the Wildcards section and try it again with the * in place. Try it also in different directories, and with the * surrounded by double quotes, and try it preceded by a backslash ( \* )
In case you don’t have access to a shell at the moment (it is very useful to have a shell to hand whilst reading this tutorial), the results of the above two scripts are:
and, for the second example:
So, as you can see, for simply loops through whatever input it is given, until it runs out of input.
While Loops
while loops can be much more fun! (depending on your idea of fun, and how often you get out of the house. )
What happens here, is that the echo and read statements will run indefinitely until you type «bye» when prompted.
Review Variables — Part I to see why we set INPUT_STRING=hello before testing it. This makes it a repeat loop, not a traditional while loop.
The colon ( : ) always evaluates to true; whilst using this can be necessary sometimes, it is often preferable to use a real exit condition. Compare quitting the above loop with the one below; see which is the more elegant. Also think of some situations in which each one would be more useful than the other:
Another useful trick is the while read loop. This example uses the case statement, which we’ll cover later. It reads from the file myfile.txt , and for each line, tells you what language it thinks is being used.
(note: Each line must end with a LF (newline) — if cat myfile.txt doesn’t end with a blank line, that final line will not be processed.)
This reads the file » myfile.txt «, one line at a time, into the variable » $input_text «. The case statement then checks the value of $input_text . If the word that was read from myfile.txt was «hello» then it echo es the word «English». If it was «gday» then it will echo Australian . If the word (or words) read from a line of myfile.txt don’t match any of the provided patterns, then the catch-all «*» default will display the message «Unknown Language: $input_text» — where of course «$input_text» is the value of the line that it read in from myfile.txt . while3.sh
Let’s say our myfile.txt file contains the following five lines:
A sample run of this script would go like this:
A handy Bash (but not Bourne Shell) tip I learned recently from the Linux From Scratch project is:
instead of the more cumbersome:
And this can be done recursively, too:
We will use while loops further in the Test and Case sections.
Источник
Bash While Loop Examples
H ow do I use bash while loop to repeat specific task under Linux / UNIX operating system? How do I set infinite loops using while statement? Can you provide me the while loop examples?
The bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.
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
Источник