sandra_henrystocker
Unix Dweeb

Options for looping in bash

How-To
Oct 23, 20152 mins

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.

#!/bin/bash

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

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 ”

#!/bin/bash

while read line; do
    echo $line
done 

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.

#!/bin/bash

IFS=$'n'       # newline is the separator

for line in `cat sample.txt`
do
    echo $line
done
With IFS being set as shown, the output from this script would look like this:
$ ./loop0
Once
upon
a
time,
there
was
a
peasant
who,
in
spite
of
his
poverty,
...

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.

sandra_henrystocker

Sandra Henry-Stocker was a programmer, Linux systems administrator, security engineer and Linux journalist for most of her 30-year career. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she's chasing the bears away from her bird feeders. Tune into her 2-Minute Linux video tutorials and take command of your command line.

More from this author