It is usually true on unix systems that the number of links to a directory is the number of subdirectories plus 2. However there are cases where this is not true:
Some unices allow hard links to directories. Then there will be more than 2 links that do not correspond to subdirectories.
There are filesystems where directories do not have entries for .
and ..
. The GNU find manual mentions some examples in the discussion of its -noleaf
option (which disables an optimization that assumes that .
and ..
exist in all directories): “CD-ROM or MS-DOS filesystems or AFS volume mount points”
An almost reliable way to count the number of subdirectories (it may still fail if a file name contains a newline character) is
$(($(LC_ALL=C ls -la /path/to/directory | grep '^d' | wc -l) - 2)
A more reliable way uses shell globs */
and .*/
; as usual handling the case where the pattern doesn't match is a bit of a pain (except in bash and zsh where you can turn on the nullglob
option).
-type d
, but: 1. this requires GNU find; 2. you need to subtract 1 for the starting directory (or pass-mindepth 1
). – Gilles 'SO- stop being evil' Oct 04 '10 at 20:11