bashfinddirname

Bash - dirname not working with substitution


When using find with $(dirname {}), it always just outputs "." as the dirname. E.g. for:

find . -name \*.h -exec echo {} \; -exec echo $(dirname {}) \;

outputs:

./folder/folder.h
.
./folder/sub_folder/sub_folder.h
.
./test.h
.

But I would expect this:

./folder/folder.h
./folder
./folder/sub_folder/sub_folder.h
./folder/sub_folder
./test.h
.

Interestingly, creating a new shell for each find generates the correct output:

find . -name \*.h -exec sh -c 'echo $0; echo $(dirname $0);' {} \;

Solution

  • This line gives what you want:

    find . -name *.h -print -exec dirname {} \;