I am a newbie in Unix. I have a requirement in which I have to put the output of find statement in array because later in the script I have to use the output lines one by one. My find statement will retrieve me the location of directories based on the condition.

Here are the find statements:

find blah -mindepth 3 -maxdepth 3 -type d  -regex ".*/V[0-9]+/wsdls+" 
  • i got a solution for this.. array=($(find blah -mindepth 3 -maxdepth 3 -type d -regex ".*/V[0-9]+/wsdls+")) i=0 for file in "${array[@]}" do echo "${file}" let i++ done but here the strange thing is after executing this though i am able to see data properly but in every line it's saying i++ is not a valida command..and as soon as i removed the i++, then it gave me the data properly..my question is how it is happening as we are not increasing the value of i..
    – Ankit
    Apr 20, 2011 at 12:10
  • If you found an answer, please post it as an actual answer and not a comment.
    – Wuffers
    Apr 20, 2011 at 12:20
  • hard to give you help when we can't see the newlines in your code. Please put it in an answer. Apr 20, 2011 at 13:21

2 Answers 2


You can do this:

array=( $(find blah -mindepth 3 -maxdepth 3 -type d -regex ".*/V[0-9]+/wsdls+") )

# loop over it
for i in ${array[@]}
    echo $i

# or in a while loop
while [ $i -lt ${#array[@]} ]
    echo $i: ${array[$i]}
  • 6
    You'll need to set IFS=$'\n' first though: in case any of the filenames have spaces, you want to keep them as a single array element. The you'll also want to use double quotes when referencing the array: for i in "${array[@]}" Apr 20, 2011 at 13:15
  • 1
    This is quite old, but this should have been the accepted answer. It works out quite well, and the comment from @glennjackman is also quite useful.
    – casper
    Sep 7, 2018 at 16:31
  • 1
    A clarification to @glennjackman's answer is that the IFS=$'\n' needs to be at the start of the assignment statement, not in the find subshell; e.g. IFS=$'\n' array=(...).
    – devstuff
    Nov 13, 2018 at 1:30

This answer on stackoverflow has all the details and also some alternatives. But essentially, a reliable way to do it is:

while IFS=  read -r -d $'\0'; do
done < <(find Where What... -print0)

Using -print0 for the output of find and a null byte as delimiter for read avoids all the pitfalls created by filenames with spaces or worse.

And to iterate over the filenames in the array, use quotes around the array :

for file in "${array[@]}"; do
    echo "$file"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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