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 
spaced name 

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

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.


  • Maybe files=( /path/wanted/* )
    – ImHere
    Nov 23 '19 at 9:04
  • Sure, that works too if it is okay to store the complete path to each file.
    – Freddy
    Nov 23 '19 at 9:09
  • I don't see why that would be a problem, but in that case, this files=( * ) works perfectly well without a loop.
    – ImHere
    Nov 23 '19 at 13:11
  • @Isaac There's no problem at all and you're right. No loop needed here. Thank you!
    – Freddy
    Nov 23 '19 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.