Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Bash array of globs with find?

Tags:

bash

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!

like image 907
stboy Avatar asked Nov 27 '25 04:11

stboy


1 Answers

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[@]}" ')'
like image 144
Fravadona Avatar answered Nov 29 '25 19:11

Fravadona



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!