2

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:

myarray=()
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?

1 Answer 1

4

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

myarray=()

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.

4
  • 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? Mar 9, 2015 at 21:18
  • 1
    File names cannot have null bytes in them. Bash strings also cannot contain nulls. Mar 9, 2015 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. Mar 9, 2015 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. Mar 9, 2015 at 21:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .