Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose I have a directory under which there are 3 files named: file1.txt,file2.txt and file3.txt.

Now how can I fill an array with those file names(I just know that all the files have certain prefix, i.e. file, after file it can be 1,2,3 etc.

share|improve this question
If you know the names what do you mean by 'find'? Do you want to create an array with these three strings in it? – Matteo Oct 4 '12 at 5:10
A=(file*); echo ${A[@]} – warl0ck Oct 4 '12 at 6:22
I have edited my explanation above. – MiNdFrEaK Oct 4 '12 at 6:39
up vote 6 down vote accepted

From Greg's Wiki: the Bash Guide entry on arrays:

while read -r -d $'\0'; do
done < <(find *.txt -print0)

There is a detailed explanation of arrays on the page that breaks this construct down element by element; it is well worth reading in full.

share|improve this answer
Find is not needed with your example, but it still gets the job done of demonstrating a safe way to use find to populate an array +1. One note is that not all version of find support -print0. – jordanm Oct 4 '12 at 6:07
You are right. Given the lack of detail around the actual problem, I thought it better to direct the OP to the Wooledge Wiki for a more thorough explanation. – jasonwryan Oct 4 '12 at 6:11
As a regular on the #bash IRC channel whose members maintain that wiki, I agree. – jordanm Oct 4 '12 at 6:13

If the files are all in the same directory, you have some other options in addition to jasonwryan's answer.

Using a glob:


Only matching the example files in the question:


If you have bash version 4 or higher, you can even glob recursively:

shopt -s globstar

Using brace expansion to restrict your array to only your example files:


Unlike the other two examples, this will populate the array with the filenames, even if they do not exist. For this reason, the brace expansion may not be desirable.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.