0

I'm using the command files=( $(ls "/path/wanted") ) to store all filenames from a directory in an array. However filenames that contain space character result in multiple array entries.

To figure out:

ls /path/wanted 
something.txt 
spaced name 
${#files[@]} 
3 

How could I map the whole filename to each array position?

artu-hnrq
  • 297

1 Answers1

3
shopt -s nullglob # enable nullglob
#shopt -s dotglob # enable dotglob too if desired

cd /path/wanted
files=( * )
cd -

# do something with "${files[@]}" or "${#files[@]}"

shopt -u nullglob # disable nullglob
#shopt -u dotglob # disable dotglob if enabled

With nullglob disabled (default) the array would contain one element containing the glob pattern * if there are no files in the directory. With nullglob enabled the array will be empty.

The same applies to dotglob: If disabled, dotfiles must be matched explicitly with a pattern like .[^.]* (the [^.] is used to not match the current directory . and the parent directory ..). With dotglob enabled, the pattern * also matches files starting with a dot.

Related:

Freddy
  • 25,565