bash script space question

dualblade

Supreme [H]ardness
Joined
Nov 19, 2000
Messages
4,180
i'm trying to read the contents of a directory into an array, but i'm not sure how to deal with subdirectories that have spaces.

the code i've got is like this:

Code:
for dir in `ls  /vmstorage/`
do
list[count]=$dir
echo "$count: $dir"
count=$((count+1))
done

if the subdirectory has a space, the text after the space will become a new array position. i know strings can handle having spaces, but i'm not sure how to do this correctly. any advice?
 
You need to set the word separator (which is any whitespace by default)
Code:
IFS=$'\n'
for dir in `ls  /vmstorage/`
do
list[count]=$dir
echo "$count: $dir"
count=$((count+1))
done
or use bash's built-in filename expansion
Code:
for dir in /vmstorage/*
do
list[count]=$dir
echo "$count: $dir"
count=$((count+1))
done
 
thanks so much for the quick answer. i've only been working on scripting for half a day so there's so much i don't know
 
Back
Top