Using find(1) in command substitution and quote filenames with blanks
-
27-04-2021 - |
Question
I'd like to use find inside a command substitution, where the returned filenames contain whitespace. What option do I need so it correctly quotes the filenames? I tried -print0
, but it will not work in the shell itself.
example:
command $(find . -type f) some other params
I also tried with -exec echo "{}" \;
, but that was of no help either.
If I use set -x
to display shell expansion and the actual command which is executed I get:
$ command `find -type f -printf \"%p\"\ ` some other params
++ find -type f -printf '"%p" '
+ command '"./file_with' 'blanks"' '"./another' 'file"' some other params
Where are the single quotation marks coming from and why are they applied to each "word"?
La solution
Put the find result in an array, and run command "${array[@]}" some other params
.
Autres conseils
Maybe the printf
action is more amenable to being contained in a substitution (GNU find
only, though):
command $(find . -type f -printf \"%P\"\ ) some other params
The %P
placeholder is the filename minus the argument to find
, so in cases other than find .
, you'd probably want %p
instead.
find /what/ever -name "what ever" -exec echo "\{\}" \;
works here (Ubuntu 10.04 default gterm with bash)
Just tried
find /bin -name ls -exec \{\} -lah \;
`find /bin -name ls -exec echo \{\} \;` -lah
MYCMD=`find /bin -name ls -exec echo \{\} \;` && $MYCMD -lah
MYCMD=$(`find /bin -name ls -exec echo \{\} \;` -lah) && echo $MYCMD
MYCMD=$(`find /bin -name ls` -lah) && echo $MYCMD
all work as expected