Bash: pipe 'find' output into 'readarray'

When using a pipeline, bash runs the commands in subshells. Therefore, the array is populated, but in a subshell, so the parent shell has no access to it.

Use process substitution:

readarray FILES < <(find)

Note that it doesn't work for files with newlines in their names. If that could be the case, you need a more elaborate syntax:

readarray -d '' < <(find -print0)

The correct solution is:

unset a; declare -a a
while IFS= read -r -u3 -d $'\0' file; do
    a+=( "$file" )        # or however you want to process each file
done 3< <(find /tmp -type f -print0)

That's similar to what Greg's BashFAQ 020 explains in detail and this answer covers.

Has no problem with odd named files (that contain no NUL in the name), with spaces or new lines. And the result is set in an array, which makes it useful for further processing.


readarray can also read from stdin

readarray FILES <<< "$(find . -name "file*")"; echo "${#FILES[@]}"

Tags:

Bash

Find