header image
Bash Loop Over Folder Contents
October 3rd, 2009 under Linux. [ Comments: none ]

I was writing a bash script which has to loop over several folder recently. The command

for i in $( ls ); do ...

does that. However, if the folder or file names contain whitespaces then this wont work because the for loop splits the input at whitespaces. the reason for this is because for loop uses whatever is in the $IFS environment variable and uses that as the splitter characters. By default it is set to the space character. Thus we have to change this temporarily to a line break.

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
....
IFS=$SAVEIFS

For more details see here.


 


Flickr
wavesAgain water dropsunset and fountainfountain

View All Photos

Recent Posts
Quotes
Boyd: God says you look for excuses to be alone.
Dr. House: See, that is exactly the kind of brilliance that sounds deep, but you could say it about any person who doesn't pine for the social approval of everyone he meets - which you were cleverly able to deduce about me by not being a moron. Next time, tell God to be more specific.”
IP