David
David

Reputation: 2964

Array of folder names without space in bash

I'm trying to run through a list of folders that have a space in them. The folders look something like

/Volumes/SAMPLE
/Volumes/SAMPlE 1
/Volumes/SAMPLE 2

and so on. To set up the array that contains all of these folders, I have

dirlist=(`ls -d /Volumes/*${prefix}*`);

When I run something like

for ((i = 0; i < ${#dirlist[@]}; i++))
do
    echo "${dirlist[$i]}";
done

I get the folder names, but the spaces have created separate entries:

/Volumes/SAMPLE
/Volumes/SAMPLE
1
/Volumes/SAMPLE
2
/Volumes/SAMPLE
3
/Volumes/SAMPLE
4
/Volumes/SAMPLE
5

What do I need to do for the space not to separate the array and to be included as part of the directory?

Thanks!

Upvotes: 0

Views: 178

Answers (2)

l0b0
l0b0

Reputation: 58958

Simply don't use ls:

dirlist=(/Volumes/*"${prefix}"*)

Example session:

$ cd -- "$(mktemp --directory)"
$ touch a 'foo bar' z
$ dirlist=(./*)
$ printf '%s\n' "${dirlist[@]}"
./a
./foo bar
./z

Upvotes: 4

karakfa
karakfa

Reputation: 67557

don't need arrays for this

find /Volumes -maxdepth 1 -type d -name "*${prefix}*"

however including spaces in filename and directory names is a terrible practice infected by Windows...

Upvotes: 0

Related Questions