Bash: How to Read Filenames into an Array


Often you may want to use Bash to read the filenames from a directory into an array:

You can use the following basic syntax to do so:

shopt -s nullglob

my_array=(*)

This particular example reads all of the filenames from the current directory into an array named my_array.

Once the filenames are in the array, you can view them all by using the following statement:

echo "${my_array[@]}"

If you would like to only view a specific filename, such as the first filename in the array, then you can use the following syntax:

echo "${my_array[0]}"

Note: The first element of an array in Bash has an index value of 0.

The following example shows how to read filenames into an array in practice.

Example: How to Read Filenames into an Array in Bash

Suppose that we would like to read all filenames from our current directory into an array.

We can first use the ls statement to view all filenames in our current directory:

We can see that the current directory contains four filenames.

We can use the following syntax to read each of these filenames into an array named my_array:

shopt -s nullglob

my_array=(*)

We can then uses the following syntax to view each of the filenames in the array:

echo "${my_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash read filenames into array

Notice that when we use the echo statement to view the elements in the array we can see that it contains each of the four filenames from our current directory.

Note that we could also use the following syntax to only view the first filename in the array:

echo "${my_array[0]}"

The following screenshot shows how to use this syntax in practice:

This returns athletes.txt, which represents the first filename in the array.

Feel free to replace the 0 in the brackets to instead return a filename from a different index position in the array.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Read Lines of File into Array
Bash: How to Read Columns from CSV File into Arrays
Bash: How to Count Number of Columns in File

Leave a Reply