Bash, for-loops and newline instead of whitespace

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Bash, for-loops and newline instead of whitespace

Post 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.
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply