Tip: how to get the deepest directories

A couple of times there was the question: in a directory hierarchy how to display the deepest directories only.
For example in Help with listing only subfolders.
My hot solution at that time was (in short)

find . -depth -type d | awk -F / 'NF>=p; {p=NF}'

But another article has opened my eyes for the cool solution

find . -depth -type d -links 2

:cool:
In fact I had implemented that a long time ago in a Unix cleantmp solution; the task is to run rmdir on non-empty directories, and in the absence of -empty the -links 2 is the closest approach: an rmdir can only work on the deepest directories.

3 Likes

Just found another optimization:

find . -type d -links 2 -prune

Skips the readdir:s of the deepest directories.

1 Like

That is cool approach, even though it is not foolproof, since an extra hard link will mess up the result, although in practice that probably/usually will not be the case,.

1 Like

Good point. Yes, in practise there is hardly a need for hard-linking a directory. And there are even some risks.

The POSIX standards don't require a directory to contain directory entries for dot and dot-dot. I assume that any filesystem type that does not include entries for dot and dot-dot would have a link count of 0 (not 2) for an empty directory.

But, I have never used a filesystem type that does not contain entries for dot and dot-dot. Does anyone know if any of these filesystems still exist?

1 Like

For the 101% safety

find . -type d -links -3 -prune 

There are certainly some file systems without dot and dot-dot (HighSierra/ISO9660?). However, I think a LUnix driver will always emulate them.

find(1) - Linux manual page

To be honest, I never looked to see if a mounted CDROM used .. and . Good question, Don.

I assume this would apply to SMB mounts from FAT32 filesystems.