BASH: Handling File Names With Spaces on loop script with bash




--one upon a time--
if you try to process a for loop on file name with spaces in them, you are going to have some problem.
By default, the shell splits the output of a command on spaces, tabs, and newlines. it's called IFS variable

--example--
we have list of file on foltest:
/some/where/aku hebat
/some/where/cema ngat
and than the script is:

#!/bin/bash
#darKonsole
#^_^
NAMES=`cat /some/where/foltest`
for file in $NAMES
do
find /ifs/admedika/ftp/FTP/$file/ -type f -exec ls {} \;
done

--theory jowo--
the long long explanation is  To figure out what to set file to, the shell has to take the output of find and interpret it somehow, otherwise file would just be the entire output of find.

The shell reads the IFS variable, which is which is set to by default.

Then it looks at each character in the output of find. As soon as it sees any character that's in IFS, it thinks that marks the end of the file name, so it sets file to whatever characters it saw until now and runs the loop. Then it starts where it left off to get the next file name, and runs the next loop, etc., until it reaches the end of output.

To tell it to only split the input on newlines, you need to do
IFS=$(echo -en "\n\b")
before your for ... find command.

That sets IFS to a single newline, so it only splits on newlines, and not spaces and tabs as well.
That is probably enough to get your script working, but if you're interested to handle some other corner cases properly, read on...

--implementasi--
now lets take the theory to the reality..., are you ready ????
this is the script we will got:
#!/bin/bash
#darKonsole
#^_^

#save default value IFS
darkIFS=$IFS
IFS=$(echo -en "\n\b")

NAMES=`cat ftpfoltest`
for i in $NAMES
do
find /ifs/admedika/ftp/FTP/$i/ -type f -exec ls {} \;
done

# restore $IFS
IFS=$darkIFS--note--
--note--
for good environment add default value of IFS to the some variable and than restore it back when the looping is done


Previous
Next Post »

comment please ... ConversionConversion EmoticonEmoticon

Thanks for your comment