3

In bash, if try to run the function basename within the -exec option of find, it doesn't seem to do anything. As an example:

find . -name "*pdf" -exec  echo $(basename {}) \;

yields the filename including the directory, i.e., the same as the result of

find . -name "*pdf" -exec  echo {} \;

Why does this happen?

JeffDror
  • 191
  • 1
  • 6

1 Answers1

4

The $(basename {}) snippet is parsed by your shell before find is executed. The result is {}. That's why the two commands are the same.

To make it work as you wanted you may spawn another shell that will handle $() on its own. Quoting with '' prevents the outer shell from processing $():

find -name "*pdf" -exec sh -c 'echo $(basename "$1")' sh {} \;

Note: the first version of this answer used sh -c 'echo $(basename {})'. This is wrong, see this other answer.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202