Bash, for-loops and newline instead of whitespace
Posted: Mon Dec 14, 2009 3:01 pm
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:
It seems like IFS is being ignored, but why?
Because the code is indented. Eliminate the spaces on the left side and it works:
It looks ugly, but it works.
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
}
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
}