A while loop is a loop that repeats a series of commands for as long as a given condition is true. In this Course, you'll be introduced to while loops.
Learning Objectives
- Learn how and when to create infinite while loops.
- Understand the different ways to control the number of times a loop is performed.
- Learn how to limit the number of loops, end a loop based on user input, and end a loop based on the exit status of a given command.
- Learn how to read a file one line at a time.
- Understand how to use the break and continue statements to selectively operate on items in a loop.
Intended Audience
This Course is intended for anyone looking to learn more about bash scripting and shell programming.
Prerequisites
To get the most out of this Course, you should have some basic knowledge of the command line, but it's not essential.
In this lesson, you'll be introduced to while loops. We'll talk about how and when to create infinite while loops. Next, you'll learn about different ways to control the number of times a loop is performed. You'll learn how to limit the number of loops, how to end a loop based on user input and how to end a loop based on the exit status of a given command. I'll show you one of the most common use cases for a while loop, which is to read a file one line at a time. Finally, you'll learn how to use the break and continue statements to selectively operate on items in a loop.
A while loop is a loop that repeats a series of commands for as long as a given condition is true. This condition could be some sort of tests such as checking to see if a variable as a certain value or checking to see if a file exists for example. The condition could also be any command. If the command succeeds and returns a zero exit status, then the while loop will continue. When the command fails and returns a non-zero exit status, the condition is false and the while loop stops. If the condition is never true, then the commands inside the while loop are never executed. Typically, the while loop checks for a condition that will be changed by the commands inside the while loop.
If the condition is examining the value of a variable, that variable will be in manipulated and changed in some way, by the commands inside the while loop. If the condition is checking the exit status of a command, then the commands in the while loop will eventually cause the exit status of that command to be non-zero or false. If the condition that is being tested, always returns true, then the while loop will never exit. If this happens, you'll need to interrupt the script by hitting Ctrl + C if you're running it interactively from the command line, otherwise you'll need to use the kill command to kill the process. Typically, when this happens it's due to a bug and logic error in the script.
There may be cases where you want an infinite loop. If so, you can simply make the condition always return true by using the true command. The true command always exits with a zero exit status, and thus is always true. If you want to create some type of service or Daemon, you can use this technique. You would simply start your shell script in the background, and it would continually run until it was killed. When you do this, there are typically a series of commands in the while loop and then asleep command to pause the execution of the script for a given number of seconds.
Let's take a look at a couple of actual examples of while loops. One thing you can do with while loop is control the number of times it loops. One common pattern you'll see is to create an index variable, check the value of that variable then increment that variable at the end of the command section of the while loop. This example demonstrates one way to loop five times. First, index is set to one. The commands in the while loop get executed because index is less than six. The echo command is executed in displays creating project -1, then the maker command is executed. Finally, the index variable is incremented by one. This is done by using something called arithmetic expansion. You can enclose a mathematical expression inside double parentheses. The double plus sign is the increment operator and it simply adds one to the variable it follows. The first time this loop is executed index will be incremented from one to two. The next iteration of the loop continues because index or two is less than six. This repeats until index is set to six on the fifth loop. Six is not less than six, so the while loop is complete and the script will continue.
Here's the output in the previous script, as you can see it completed the loop five times. Here's an example where user input populates the variable that is being used to control the while loop. Here we're asking a user for a name, the first recommand populates the name variable, whether users input. The next recommand displays back what they entered and ask them if it's correct, then input is stored in the correct variable. If the user answers anything other than a lowercase y to that question, the loop repeats. When the correct variable is set to lowercase y the loop is complete and the script continues after the while loop.
Here's what this script would look like, the first time the loop executes something other than y was entered, so it repeats the loop. Once y is entered the loop exits. Let's look at an example where you need to check the return code of a command. Let's say you have a script that runs on a database server and perform some sort of maintenance or backup. Let's make that script wait until the application server is off the network before it continues, this way we can know that the application is not actively using the database, while we are performing our maintenance. We do this by using the ping command, using - c 1 causes a count of one packet to be sent to the server. We also redirect the output to dev/null, since we don't really need to see the output. If the ping command succeeds, then an exit status of zero is returned. If it fails in a non-zero exit status is returned. While the server is pingable, the condition is true and the loop continues. Once the ping command fails, the script continues. Here's some sample output from the previous script. While the server is pingable, the loop continues. Once it can't be pinged, the loop exits and the script continues.
Jason is the founder of the Linux Training Academy as well as the author of "Linux for Beginners" and "Command Line Kung Fu." He has over 20 years of professional Linux experience, having worked for industry leaders such as Hewlett-Packard, Xerox, UPS, FireEye, and Amazon.com. Nothing gives him more satisfaction than knowing he has helped thousands of IT professionals level up their careers through his many books and courses.