Page 1 of 1

Bash, for-loops and newline instead of whitespace

Posted: Mon Dec 14, 2009 3:01 pm
by ^rooker
I wanted to go through a list of files in a for loop, but each filename was on its own line and some filenames contained whitespace characters.
By default, BASH's for loop uses the whitespace character as separator. This can be changed by setting the variable "IFS" to something else, as found on the web.

This is actually true, but there's a caveat!

Example:

Code: Select all

function test
{
    IFS="
    "
    FILES=`find . -name *.txt`
    for file in $FILES; do
       echo $file
    done
}
It seems like IFS is being ignored, but why?
Because the code is indented. Eliminate the spaces on the left side and it works:

Code: Select all

function test
{
IFS="
"
    FILES=`find . -name *.txt`
    for file in $FILES; do
       echo $file
    done
}
It looks ugly, but it works.