Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading filenames into an array

Tags:

bash

unix

cygwin

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?

like image 289
dublintech Avatar asked Jun 11 '12 13:06

dublintech


People also ask

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

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.

like image 121
Dennis Williamson Avatar answered Oct 01 '22 03:10

Dennis Williamson