I need to loop through the files in a directory and process the files. But some of the filenames contain spaces.
Here is a little test script I've been using to experiment. (I'm not really going to call 'echo', I'm doing some other processing.) Everything I try fails. How can I do this??
#!/bin/sh
# spacetest
DIR="/tmp/spacetest$$"
rm -rf $DIR
mkdir -p $DIR || exit 1
touch $DIR/{"a b","c d"}
# This works, when I itemize filenames a priori
set "a b" "c d"
for x in "$@"; do
echo $x
done
echo Test 1: # Fails
for x in $(find $DIR -mindepth 1 -printf '"%f" '); do
echo $x
done
echo Test 2: # Fails
set $(find $DIR -mindepth 1 -printf '%f ')
for x in "$@"; do
echo $x
done
echo Test 3: # Fails
set $(find $DIR -mindepth 1 -printf '"%f" ')
for x in "$@"; do
echo $x
done
echo Test 4: # Fails
_list="$(find $DIR -mindepth 1 -printf '"%f" ')"
set $_list
for x in "$@"; do
echo $x
done
rm -rf $DIR
> cat see_blanks
ls -l file*
ls | grep "file" >f_list
while read filename
do
echo "### echo"
echo $filename
echo "### ls"
ls $filename
echo "### ls in quotes"
ls "$filename"
echo "### play with IFS"
OLDIFS=$IFS
IFS="~"
ls $filename
IFS=$OLDIFS
done<f_list
prorgam execution
> see_blanks
-rw-rw---- 1 xxx dp 0 Nov 28 10:04 file 04
-rw-rw---- 1 xxx dp 0 Nov 28 10:04 file01
### echo
file 04
### ls
ls: cannot access file: No such file or directory
ls: cannot access 04: No such file or directory
### ls in quotes
file 04
### play with IFS
file 04
### echo
file01
### ls
file01
### ls in quotes
file01
### play with IFS
file01
So, if I use the variable inside quotes, it works. And if I reset the IFS setting then I do not break-apart the commands at each space.