Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

While Loops

The other most common form of loop in the shell is the while loop. As its name suggests, it keeps on executing the code in the body of the loop while the condition that it tests for remains true. This is very useful when you cannot predict when the condition that you are looking for will occur. It can also be useful when you want to keep on doing something until it makes a certain condition occur. The structure of a while loop is that you define the condition and then the code for it to execute while the condition remains true. This loop keeps doubling the value of a variable until it exceeds 100.

download.eps
cat while.sh
#!/bin/bash
i=1
while [ "$i" -lt "100" ]
do
  echo "i is $i"
  i='expr $i \* 2'
done
echo "Finished because i is now $i"
$ ./while.sh
i is 1
i is 2
i is 4
i is 8
i is 16
i is 32
i is 64
Finished because i is now 128
$

while.sh

Because the condition is that i is less than 100, i gets to 64 and then the loop goes back to the test, which passes. The body of the loop is entered again, sets i=128, and when execution goes back to the test for the eighth time, the test fails. The shell exits the loop, continuing with the echo statement, which displays the current value of i, which is 128. So the loop does not stop the variable from getting over 100, but refuses to run the loop while i is over 100.

When to Use While Loops

while loops are most useful when you don’t ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads