You will also learn how to use loops to traverse array elements. Furthermore, you will learn how to use break and continue statements to control loops, and finally, you will learn how to create infinite loops.
If you are following this tutorial series from start, you should be familiar with arrays in bash. For loops are often the most popular choice when it comes to iterating over array elements.
For example, the following prime.sh script iterates over and prints out each element in the prime array: You can also use a continue statement to skip a loop iteration.
In most cases, infinite loops are a product of a human logical error. In some cases, you may want to intentionally create infinite loops to wait for an external condition to be met on the system.
How do I use bash while loop to repeat specific task under Linux / UNIX operating system? 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 detailsDifficulty Easy (RSS)Root privilegesNoRequirements BASH or ASH on Linux/Unix-like systems Time 5 m The syntax is as follows: Infinite loops occur when the conditional never evaluates to false.
You can easily evaluate the options passed on the command line for a script using while loop: You can do early exit with the break statement inside the while loop.
We learned that bash while loop executes while a condition is true. Making statements based on opinion; back them up with references or personal experience.
In scripting languages such as Bash, loops are useful for automating repetitive tasks. We’ll also show you how to use the break and continue statements to alter the flow of a loop.
The while loop is used to perform a given set of commands an unknown number of times as long as the given condition evaluates to true. Otherwise, if the condition evaluates to false, the loop is terminated, and the program control will be passed to the command that follows.
In the example below, on each iteration, the current value of the variable I is printed and incremented by one. Instead of controlling the while loop with a condition, we are using input redirection (< “file”) to pass a file to the read command, which controls the loop.
By default, the read command trims the leading/trailing whitespace characters (spaces and tabs). In the following example, the execution of the loop will be interrupted once the current iterated item is equal to 2.
In the following below, once the current iterated item is equal to 2 the continue statement will cause execution to return to the beginning of the loop and to continue with the next iteration. The while loop repeatedly executes a given set of commands as long as a condition is true.
If you have any questions or feedback, feel free to leave a comment. Last updated: 2020-09-26The loop constructs are in every programming language, including Bash.
The loop constructs are common programming building blocks that allow us to repeat the execution of a section of code through an iteration. The count-controlled loop repeats the execution of a section of code for a certain number of times.
The infinite loop repeats the execution of a section of code forever or until an exception arises. The collection-crontolled for-loop (for each or range) The below syntax is used in a collection-controlled for loop to iterate over a list and execute a set of commands once for each member.
It is similar to a for each statement in other languages and can be used to loop over a range of numbers or words. The bash while -loop construct can be used to create a condition-controlled loop using a , a , or based on the exit status of any command.
The loop will execute as long as the test command has an exit code status of zero. This means that you can also use the while -loop construct as a way to do an infinite loop when combined with the true command or the (i.e. by using the colon character :).
Using a while -loop is generally the recommended way in Bash for iterating over each line of a file or stream. The bash until-loop construct can be used to create a condition-controlled loop using a , a , or based on the exit status of any command.
The until-loop is similar to the while -loop except that it will execute as long as the test command has an exit code status which is not zero. This means that you can also use the until-loop construct as a way to do an infinite loop when combined with the false command.
Both the break and continue commands can be used inside a for, while, and until loop and can take an optional parameter . The parameter is optional and allows you to specify which level of enclosing loop to exit, the default value is 1.
The parameter is optional and allows you to specify which level of enclosing loop to resume from, the default value is 1. In Bash, you must use a read- while loop or the map file built-in command to safely parse the line of a file.
When iterating over a list of files with a for loop, you shouldn’t use the ls command or other alternative command line as it may return incorrect results due to newline characters, white spaces, or any other wildcards present in the filename. Instead, you should directly use the bash filename expansion using lobbing and test that the file exists using a conditional expression to prevent the output of the lobbing pattern as a string when no filename matches the pattern.
Alternatively, you can use the null glob shell options, read more in my post on What Is The Best Way To Count Files In A Directory? The while construct allows for repetitive execution of a list of commands, as long as the command controlling the while loop executes successfully (exit status of zero).
CONTROL-COMMAND can be any command(s) that can exit with a success or failure status. As long as this command fails, the loop continues.
As we already explained previously, the “;” may be replaced with one or more newlines wherever it appears. How you can use while loop in bash script is shown in this article by using different examples.
The starting and ending block of while loop are defined by do and done keywords in bash script. Open a text editor to write bash script and test the following while loop examples.
Break statement is used to exit from the loop early based on a particular condition. Create a new bash file named while2.sh with the following code.
According to the script it will terminate after 6 times iteration for break statement. Create a new bash file named while3.sh with the following code.
In this example, the loop will iterate for 5 times, but it will not print all 5 positions. Sometimes, it is required to declare infinite loop for various programming purposes.