I am trying to construct a compound -name
primary for the find
command from an arbitrary number of strings in an array, of the form \( -name ${a[0]} -or -name ${a[1]} -or -name ${a[2]} ... \)
. While explicitly typing the name primary into the terminal works, storing it in a variable and recalling it by parameter expansion does not. Since expansion will take place before find
runs, I assume the problem has something to do with quoting of the expanded variable.
Below is a minimal example for n=2 names, either typed literally or recalled from a variable. While I realize that I could pipe to grep
, I would prefer to do everything with find
in this case.
$ ls
a1 a2 b1 b2 c1 c2
$ find . \( -name a\* -or -name b\* \)
./a1
./a2
./b1
./b2
$ names="\( -name a\* -or -name b\* \)"
$ printf "%s\n" "$names"
\( -name a\* -or -name b\* \)
$ find . $(printf "%q" "$names")
find: -name\: unknown primary or operator
$ find . $(printf "%s" "$names")
find: \): unknown primary or operator
$ find . $names
find: \): unknown primary or operator
$ find . "$names"
find: \( -name a\* -or -name b\* \): No such file or directory