Options for looping in bash

hoop tony fischer
Credit: flickr / Tony Fischer

Looping in bash is easy. You just use a for or a while statement. But, when you want to process a complete line of text from a file in each pass through the loop, you might have to work a little harder as the simple for loop (like that shown below) would loop once for each word (piece of text) in the file.


for word in `cat sample.txt`
    echo $word

The way I've always handled this issue in the past is to use a slightly different syntax. If I use a while statement and direct the file to be read by preceding it with a "<" sign, I can get the effect I need. And, though I normally use for loops almost exclusively, I usually only have to scratch my head for a minute or so to remember how this works.


while read line; do
    echo $line
done <sample.txt

Another way to do the same thing, a technique that I only recently glommed onto, is to specify the field separator for your while statement using the IFS (internal field separator) variable and set it to the newline character as shown in the alternate form of looping shown below, making en entire line of text the "field" that you're working with. This will produce the same output as the earlier loop, but you might like the look of it better. And, if you end up looping numerous times in the same script, you only have to set up IFS once.


IFS=$'\n'       # newline is the separator

for line in `cat sample.txt`
    echo $line
$ ./loop0

Just remember that, if you use the IFS variable, it will affect all of the looping in the particular script that you're working on -- beyond the point of its being set up.

This article is published as part of the IDG Contributor Network. Want to Join?

To express your thoughts on Computerworld content, visit Computerworld's Facebook page, LinkedIn page and Twitter stream.
Fix Windows 10 problems with these free Microsoft tools
Shop Tech Products at Amazon
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.