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?

  • 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 – Josh Bothun Mar 23 '13 at 00:27
  • Possible duplicate of [Reading filenames into an array](http://stackoverflow.com/questions/10981439/reading-filenames-into-an-array) – miken32 Feb 12 '16 at 01:29

1 Answers1

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.

Community
  • 1
  • 1
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • 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? –  Mar 23 '13 at 00:51
  • @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. – Gordon Davisson Mar 23 '13 at 01:00
  • Awesome answer, helped a ton! – dardo Aug 20 '14 at 16:42
  • Thanks... 3 hours searching how to use vars as directories path. Thanks a lot! – equiman Mar 30 '17 at 00:59