3

I am having trouble reading file into an array in bash.

I have noticed that people do not recommend using the ls -1 option. Is there a way to get around this?

2
  • 4
    Can you clarify a bit more about what you are trying to do? The ls command is for listing a directory, not reading files Commented Mar 23, 2013 at 0:27
  • Possible duplicate of Reading filenames into an array Commented Feb 12, 2016 at 1:29

1 Answer 1

17

The most reliable way to get a list of files is with a shell wildcard:

# First set bash option to avoid
# unmatched patterns expand as result values
shopt -s nullglob
# Then store matching file names into array
filearray=( * )

If you need to get the files somewhere other than the current directory, use:

filearray=( "$dir"/* )

Note that the directory path should be in double-quotes in case it contains spaces or other special characters, but the * cannot be or it won't be expanded into a file list. Also, this fills the array with the paths to the files, not just the names (e.g. if $dir is "path/to/directory", filearray will contain "path/to/directory/file1", "path/to/directory/file2", etc). If you want just the file names, you can trim the path prefixes with:

filearray=( "$dir"/* )
filearray=( "${filearray[@]##*/}" )

If you need to include files in subdirectories, things get a bit more complicated; see this previous answer.

Sign up to request clarification or add additional context in comments.

4 Comments

I am in the directory of the array. So, the first one filearray=( * ) this will get all of the files into the array with each file having their own index?
@sinful15: Yes. BTW, be sure to put references to the filenames in doublequotes, as in "${filearray[1]}" for just one file or "${filearray[@]}" for the full list.
Awesome answer, helped a ton!
Thanks... 3 hours searching how to use vars as directories path. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.