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

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

does that. However, if the folder or file names contain whitespaces then this wont work because the

loop splits the input at whitespaces. the reason for this is because 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.

1
2
3
4
SAVEIFS=$IFS<br />
IFS=$(echo -en "\n\b")<br />
....<br />
IFS=$SAVEIFS
SAVEIFS=$IFS<br />
IFS=$(echo -en "\n\b")<br />
....<br />
IFS=$SAVEIFS

For more details see here.