Search code examples
arraysbashfindgnu-findutils

Is there a way to pass options as an array to find command in bash?


In rsync I can just define my exclusions/options in an array and use those arrays in the subsequent command, e. g.

rsync "${rsyncOptions[@]}" "${rsyncExclusions[@]}" src dest

I wanted to achieve the same using the find command but I couldn't find a way to make it work:

findExclusions=(
    "-not \( -name '#recycle' -prune \)"
    "-not \( -name '#snapshot' -prune \)"
    "-not \( -name '@eaDir' -prune \)"
    "-not \( -name '.TemporaryItems' -prune \)"
)
LC_ALL=C /bin/find src -mindepth 1 "${findExclusions[@]}" -print

In whatever combination I try to define the array (single vs double quotes, escaping parentheses) I always end up with an error:

find: unknown predicate `-not \( -name '#recycle' -prune \)'
# or
find: paths must precede expression: ! \( -name '#recycle' -prune \)

What is the correct way to do this?


Solution

  • The issue here is that "-not \( -name '#recycle' -prune \)" is not one argument, it is 6 arguments. You could write it like so:

    findExclusions=(
        -not '(' -name '#recycle' -prune ')'
        -not '(' -name '#snapshot' -prune ')'
    )