Bash While Loops – A Simple How To

I work with a lot of people that just don’t understand what a while loop is, how it functions and most of all how to write one.

First off while loops are very useful for working with one-liners and data received on the command line. A while loop executes a portion of code until a condition that was true becomes false. So usually you use them with a counter like so:

count = 0
while [ $count -lt 10 ]; do
    echo $count
    let count+=1
done

This says line by line:
1. Setup a variable named $count and give it a value of 0.
2. While the variable $count is less than 10 print the number then add 1 to $count.

So when we first enter the while loop we can see the condition is true (0 < 10 == TRUE). Each iteration of the loop adds 1 to $count eventually making the condition false at which point your program proceeds.

Generally speaking though I don’t use bash for something like this. Most of my WHILE loops look like this:

cat some_file.txt | while read line; do echo $line; done

So what is going on above seeing as it looks nothing like what you just saw. First we say `cat some_file.txt` which means dump the contents of the file to STDOUT (your terminal) then we PIPE that to a WHILE loop. So the condition here is `read line`, in bash the read command takes a line of input and returns a 0 (The 0 means true in Bash although almost every other language disagrees) so in this case when read line receives a line of input it is really the same as writing:

while [ true ]; do

So it continues to move forward until ‘read line’ becomes false. Such as at the end of input or the end of a file.

Write a Comment

Your email address will not be published. Required fields are marked *