- Unix / Linux — Shell Loop Types
- Nesting Loops
- Nesting while Loops
- Syntax
- Example
- Unix / Linux — Shell Loop Control
- The infinite Loop
- Example
- The break Statement
- Syntax
- Example
- The continue statement
- Syntax
- Example
- While loop
- Contents
- The while loop syntax
- while loop Example
- Using ((expression)) Format With The While Loop
- Reading A Text File With Separate Fields
- 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
- 7. Loops
- For Loops
- While Loops
Unix / Linux — Shell Loop Types
In this chapter, we will discuss shell loops in Unix. A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers −
You will use different loops based on the situation. For example, the while loop executes the given commands until the given condition remains true; the until loop executes until a given condition becomes true.
Once you have good programming practice you will gain the expertise and thereby, start using appropriate loop based on the situation. Here, while and for loops are available in most of the other programming languages like C, C++ and PERL, etc.
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another similar one or different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming requirement in a similar way −
Nesting while Loops
It is possible to use a while loop as part of the body of another while loop.
Syntax
Example
Here is a simple example of loop nesting. Let’s add another countdown loop inside the loop that you used to count to nine −
This will produce the following result. It is important to note how echo -n works here. Here -n option lets echo avoid printing a new line character.
Источник
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 break statement
The continue statement
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 −
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 −
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 −
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 −
Upon execution, you will receive the following result −
Источник
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:
Источник
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
Источник
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.
Источник