0

I would like find to execute a different command depending on what the stats of a file are.

If I run the command

find . -name "*" -exec echo {} \+

then I get the list of files in the directory. As expected, adding echo `` gives the same result:

find . -name "*" -exec echo `echo {}` \+

On the other hand, with stat the situation is different.

find . -name "*" -exec stat {} \+

works as expected. However,

find . -name "*" -exec echo `stat {}` \+

returns the error

stat: {}: stat: No such file or directory

In this case, the braces {} do not get expanded like they do in the echo example. How do I make the expansion work as expected?

Alex
  • 1,175
  • It is working as expected, surely? in the first case, echo {} is executed inside the command substitution, outputting literal {}, so the arguments to the find command become -exec {} + - whereas the execution of stat {} inside the command substitution produces an error. What is your end goal here? – steeldriver Oct 25 '23 at 00:34
  • You can't. The 'expansion' of {} to a found filename is done by find after it has found a suitable file and it exec's the program and argument(s) you specify. Process substitution with backticks or the newer/better $( ... ) syntax is done by the shell before even starting find, so none of the (possibly many) filenames that will be found in the future is yet known. You need to be a Time Lord (or companion) or god to go backward in time and make this work.; we would be interested to hear when you achieve either of those. – dave_thompson_085 Oct 25 '23 at 00:37
  • @steeldriver The end goal is to execute a different command depending on the stat output, I edited the question to specify this. – Alex Oct 25 '23 at 00:39
  • in that case you probably want a construct like -exec sh -c 'for f; do stuff with "$f"; done' find-sh {} + (unless the stat test you want to apply can be achieved via one of find's built-in tests like -size, -perm etc.) – steeldriver Oct 25 '23 at 00:58

0 Answers0