Find all end subdirectories in a tree

command linefile searchfind

given the following structure:

oz123@debian:~/ $ tree .
.
├── a
│   ├── a1
│   ├── a2
│   └── a3
├── a1
│   ├── a11
│   ├── a12
│   └── a31
├── b
│   └── b1
│       ├── b11
│       │   └── b21
│       │       └── b31
│       ├── b12
│       └── b3
└── c

16 directories, 0 files

How do I find all the end nodes?

I found the following solutions which seems to be good, but I have to proof that there is not test case which will fail it.

The help page of the -links states:

You can also search for files that have a certain number of links,
with ‘-links’. Directories normally have at least two hard links;
their . entry is the second one. If they have subdirectories, each of
those also has a hard link called .. to its parent directory. The .
and .. directory entries are not normally searched unless they are
mentioned on the find command line.

possible solution:

oz123@debian:~/ $ find .  -type d  -links 2
./a/a2
./a/a3
./a/a1
./c
./a1/a31
./a1/a11
./a1/a12
./b/b1/b12
./b/b1/b3
./b/b1/b11/b21/b31
  • Can anyone provide a better solution (without using pipes and sed, this has be performant …)
  • Will it work on any filesystem?

Best Answer

As an addition to your own solution with -links, I want to just add that it will not work on filesystems that do not follow the Unix directory-link convention. From man find on option -noleaf these are at least CD-ROM, MS-DOS filesystems and AFS volume mount points.

For a reference, this question was already discussed with different solutions which are indeed slower and usually resort to piping to sed / awk and similar.

Related Question