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.
- 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.
This Course is intended for anyone looking to learn more about bash scripting and shell programming.
To get the most out of this Course, you should have some basic knowledge of the command line, but it's not essential.
If you've ever tried to use a for loop to read a file line-by-line, you'll quickly find that it doesn't work. What happens in that situation is, the for loop will read the file word-by-word. To actually read a file line-by-line, use while in conjunction with a read command. On the last line of the while loop, use the keyword done, followed by the less than sign, followed by the file you wish to read.
This example loops through the /etc/fstab file line-by-line printing the line number followed by the actual line. We use a variable to keep track of the line numbers and increment it as we loop through the file. Here are some sample output from running that script. You'll see the line number followed by the actual contents of the line from the /etc/fstab. In this example, the fstab is five lines long. You can also read from the output of a command instead of a file. To do this, pipe the output of the command into the while loop.
Let's modify the previous example to only print out lines that contain XFS file systems. We use grep xfs /etc/fstab to extract the lines and then pipe those lines to the while loop. We simply prepend each line with xfs: followed by a space and then following it with the actual line from the fstab. Here's what that would look like using the same fstab file from the previous example. In the previous examples we've been using the read command to read the entire line into one variable. However, the read command supports splitting the data it reads into multiple variables. Each variable supplied to the read command will store one word or one field of data, with any leftover words or fields assigned to the last variable supplied to the read command.
Let's modify the previous example a bit. Here we're going to assign the first word of data to the FS variable, the second word to the MP variable, and the rest of the line to the REST variable. If you want to assign each field in the fstab its own variable, you can do that too. Here I was just going to use the first two fields and that's why I chose to use three variables. This is the output of the script. You can see that the centos-root file system gets mounted on /, while the file system labeled boot gets mounted on /boot. If you want to exit a loop before its normal ending, use the break statement. The break statement exits the loop but it does not exit the script. The script will continue after the loop.
Here's one way you could create a simple menu. This example creates an infinite loop using while true. Next it asks the user for some input and stores that input in the variable CHOICE. The case statement is used to determine what action to take based on the user's input. If one was entered, then the df command is executed and the loop repeats asking the user for input again. If two is entered, then the uptime command is executed and the loop repeats. If anything other than one or two is entered, then the break statement is executed which ends the while loop. Note that the break statement can be used with other kinds of loops, like for loops for example. If you want to restart the loop at the next iteration before the loop completes, use the continue statement. Any commands that follow the continue statement in the loop will not be executed. Execution continues back at the top of the loop and the while condition is examined again.
In this example, we loop through a list of MySQL databases. The dash capital B option to MySQL disables the ASCII table output that MySQL normally displays. The dash capital N option suppresses the column names in the output. This prevents the header from being displayed. Finally, the dash e option causes MySQL to execute the commands that follow it. Ultimately, this MySQL command lists one database per line of output. That output is piped into a while loop. The read command assigns the input to the DB variable. First we check to see if the database has been backed up recently. This is a command that I made up, perhaps it could be a call to another script. In this contrived example, the db-backed-up-recently script return zero if the database passed to it has been backed up in the last 24 hours. Otherwise it returns a one. We use an if statement to examine the return code of that script. If the database has been backed up recently, we call the continue statement which starts to loop over again. The next database is checked and the next one and so on. If the database has not been backed up recently then we go ahead and create a backup of it. Again, the backup command is something that I made up. It could be another script that actually performs the backup, for example. The main point in this example is to demonstrate the use of the continue statement. Here we avoid unnecessary work by selectively operating on the items in the while loop by using the continue statement. Like the break statement, the continue statement can be used with other types of loops.
In this lesson you learned about while loops. We talked about creating infinite loops by forcing the condition of the while loop to always be true. Next, you learned about controlling loops by counting the number of times a loop has executed by examining user input and by checking the exit status of a command. You also learned how to use the read statement in conjunction with while loops to read files line-by-line. You even learned how to assign multiple values to multiple variables at once using the read command. Finally, you learned how to further control loops with the break and continue statements.
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.