Often you may want to use the find command in Bash to find specific files in a directory and then save those results in an array.
You can use the following syntax to do so:
readarray -d '' array < <(find . -name "*2024*" -print0)
This particular example will first find all files in the current directory that contain the pattern “2024” in the filename and then save those filenames in an array named array.
The following example shows how to use this syntax in practice.
Example: How to Save Results of “find” Command to Array in Bash
Suppose that we would like to find all files in our current directory that contain the pattern “2024” somewhere in the filename.
We can use the following syntax to first print all files that contain “2024” in the filename:
find . -name "*2024*"
The following screenshot shows how to use this syntax in practice:

We can see that there are three files in our current directory that contain the pattern “2024” in the filename.
We can then use the following syntax to save each of these filenames in an array named array:
readarray -d '' array < <(find . -name "*2024*" -print0)
We can then use the following syntax to print each of the elements in this array:
echo "${array[@]}"
The following screenshot shows how to use this syntax in practice:

We can see that the array contains the following three filenames:
- coaches2024.csv
- managers2024.csv
- rosters2024.csv
Note that we can also use brackets to access a specific filename in the array.
For example, we can use the following syntax to access only the first filename in the array:
echo "${array[0]}"
The following screenshot shows how to use this syntax in practice:

Notice that this returns only the following filename:
- coaches2024.csv
You can use similar syntax to access any element in the array.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Slice an Array
Bash: How to Append Values to Array
Bash: How to Read Lines of File into Array
