(=
I smile because I find this type of issue really annoying, and for a long time had no clue how to fix it, either. However, there is some really good news for you. (=
The secret is the bash variable IFS, or the Internal Field Separator. This bash variable is what determines how bash splits word boundaries. It's default is to match a tab, a space, or a newline.
You can easily change this variable before the for loop in question to only match tabs and newlines/carriage returns, and this will cause the filenames with spaces to remain intact.
One word of caution is this:
If you're doing other field splitting, make sure to revert this value to it's original state, because you may encounter split problems due to the fact that it no longer contains a space.
Consider that the dir /tmp/IFS contains the following files:
Code:
-rw-r--r-- 1 root root 0 2005-03-09 10:30 has\ onespace.txt
-rw-r--r-- 1 root root 0 2005-03-09 10:30 nospaces.txt
-rw-r--r-- 1 root root 0 2005-03-09 10:30 other\ file.rgf
-rw-r--r-- 1 root root 0 2005-03-09 10:30 otherfile.rgf
The follow code shows how to use 'find' to display them correctly in a for loop, and then with IFS reverted back to it's original state
Code:
#!/bin/bash
# store original value, and set to catch tab(9), newline(A), and CR(D)
#
IFScopy=$IFS
IFS=$'\x09'$'\x0A'$'\x0D'
echo "IFS FIX"
for i in `find /tmp/IFS/ -type f`; do
echo "$i"
done
# revert
#
IFS=$IFScopy
echo "IFS REVERT"
# now other for loops will work as before
#
for i in `find /tmp/IFS/ -type f`; do
echo $i
done
And the output:
Code:
/usr/sbin> q.sh
IFS FIX
/tmp/IFS/other file.rgf
/tmp/IFS/nospaces.txt
/tmp/IFS/otherfile.rgf
/tmp/IFS/has onespace.txt
IFS REVERT
/tmp/IFS/other
file.rgf
/tmp/IFS/nospaces.txt
/tmp/IFS/otherfile.rgf
/tmp/IFS/has
onespace.txt
Happy bashing!