For the record, I already tried telling mgmt and the users to disallow spaces in filenames for this script, but it isn't happening for a number of ID10T-error-based reasons.
I have simple list of 3 files in a directory that are named like this:
bash-3.2$ ls -1 file*
file1
file1 part2
file1 part3
I tried this cmd to populate the array:
fileNameArray=( `ls -1 file*` )
However, I get the following results with 5 elements when I try this for-loop,
for x in ${fileNameArray[@]}
> do
> echo $x
> done
file1
file1
part2
file1
part3
So is there a way I can populate the array so the for-loop gives me 3 elements like this:
file1
file1 part2
file1 part3
Try manipulating the IFS variable:-
# After the shebang line add something like...
save_ifs="$IFS"
# Just a newline.
IFS="
"
#
# All of your code in here...
#
#
IFS="$save_ifs"
# exit # IF required with or without a code number...
EDIT:
Not saved IFS here for this demo...
Last login: Fri Apr 18 21:43:23 on ttys000
AMIGA:barrywalker~> echo "Barry Walker." > /tmp/"file 1"
AMIGA:barrywalker~> echo "Amateur Radio. " > /tmp/"file 2"
AMIGA:barrywalker~> echo "G0LCU. " > /tmp/"file 3"
AMIGA:barrywalker~> IFS="
> "
AMIGA:barrywalker~> fileNameArray=( $(ls /tmp/file*) )
AMIGA:barrywalker~> for x in ${fileNameArray[@]}; do echo "$x"; done
/tmp/file 1
/tmp/file 2
/tmp/file 3
AMIGA:barrywalker~> _
You could also try:
fileNameArray=( file* )
for x in "${fileNameArray[@]}"
do printf "%s\n" "$x"
done
PS Note that this will work even in the (absolutely horrendous) case where a filename contains a <newline> character.