I want to iterate over all the files found by find and add each one to an array. Here's what I have so far:

find . -name '*.php' -exec myarray\+=\({}\) \;
echo "${myarray[@]}"

Instead, it produces lots of this:

find: myarray+=(./somedir/somefile.php): No such file or directory

Is there a way to make this work with proper escaping?


Your aproach should be as follow. To stay on your way of thinking you'd do something like:


while IFS= read -rd '' files; do myarray+=("$files")
 done < <(find . -type f -name '*.php' -print0)

printf '%s\n' "${myarray[@]}"

As a side note. You don't need to define myarray=() the array variable at all. You can leave that out.

  • My original intent with the array was to allow the NUL character in a filename. From what I can tell, this approach does not allow them. Is that right? – AmadeusDrZaius Mar 9 '15 at 21:18
  • 1
    File names cannot have null bytes in them. Bash strings also cannot contain nulls. – Michael Homer Mar 9 '15 at 21:22
  • @AmadeusDrZaius This aproach does force read to use NUL byte as it's line delimiter. Since NUL is not a valid byte in unix filenames, this however is the safest place of feeding an array. See mywiki.wooledge.org/BashFAQ/020 for a better explanation. – Valentin Bajrami Mar 9 '15 at 21:25
  • 1
    Thanks for the confirmation. This answer made it sound as though NUL was allowed on Mac, but I guess it's just allowed by HFS+, but not by the OS. – AmadeusDrZaius Mar 9 '15 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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