stboy
stboy

Reputation: 55

How to use Bash array of globs with find?

I have an array of globs that I want to feed to find.

My array is:

arr=('a*.txt' 'b[2-5].sh' 'ab?.doc')

Here what i tried:

find . -type f -name '${arr[@]}'

Here our array may contain many elements! Thanks for your response!

Upvotes: 3

Views: 489

Answers (1)

Fravadona
Fravadona

Reputation: 17208

The way to search for multiple glob patterns with find isn't as straightforward as find -name "${arr[@]}"; you need something equivalent to:

find '(' -name 'a*.txt' -o -name 'b[2-5].sh' -o -name 'ab?.doc' ')'

note: the parenthesis aren't mandatory in your case but you'll need them for adding other operands like -type f

That said, if your starting point is a bash array containing your globs, then you could build the arguments of find like this:

arr=('a*.txt' 'b[2-5].sh' 'ab?.doc')

names=()
for glob in "${arr[@]}"
do
    [[ $names ]] && names+=( -o )
    names+=(-name "$glob")
done

find '(' "${names[@]}" ')'

Upvotes: 5

Related Questions