Re: basename is not working as expected if invoked in `` inside a find subcommand

"Andreas R." <[email protected]>
Newsgroups gmane.comp.gnu.utils
Message-ID <[email protected]>
Paul Jarc wrote:
>>> find dir1 -exec diff -q "{}" dir2/`basename {}` \;
> 
> Here, the command substitution is expanded by the shell before find
> runs.  basename sees the literal argument {}, and so it outputs {},
> and find sees dir2/{}.
> 
>>> find dir1 -exec sh -c "diff -q {} dir2/`basename {}`" \;
> 
> Here, agin, the command substitution is expanded before find runs.
> Double quotes don't prevent an inner command substitution from being
> expanded.  Single quotes will, though.  This will do what you want:
> 
> find dir1 -exec sh -c 'diff -q {} dir2/`basename {}`' \;
That works. Thanks a lot for the advice and explanation, Paul.

> But if the filename contains any whitespace or shell metacharacters,
> it'll cause trouble.  You can protect against that like this:
> 
> find dir1 -exec sh -c 'diff -q "$0" dir2/"`basename "$0"`"' {} \;
Wow. Rewritten in the form
  find dir1 -type f -exec sh -c 'echo "{}" dir2/"`basename "{}"`"' \;
it works, but I still don't understand completely why it works.
The first part "{}" is clear (I think), but how do we get
to "`basename "{}"`" ? What is the reason why "`basename {}`" doesn't work?
And where do you learn such tricks from? :)
Is there a book you would suggest (or was reading the man page enough)?

Regards,
Andreas
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.