Bash Script Reading Files of a directory into Array

bash

Solution

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.

Problem

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?

Original source

Related problems