Reading filenames into an array

dublintech picture dublintech · Jun 11, 2012 · Viewed 80k times · Source

I want to get a list of files and then read the results into an array where each array element corresponds to a file name. Is this possible?

Answer

Dennis Williamson picture Dennis Williamson · Jun 11, 2012

Don't use ls, it's not intended for this purpose. Use globbing.

shopt -s nullglob
array=(*)
array2=(file*)
array3=(dir/*)

The nullglob option causes the array to be empty if there are no matches.