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 "<" 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.
#!/bin/bash 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.
#!/bin/bash IFS=$'\n' # newline is the separator for line in `cat sample.txt` do echo $line done
$ ./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.
This article is published as part of the IDG Contributor Network. Want to Join?