2

When displaying directories using ls -l, their number of links (the second field in the output) is at least two: one for the dir name and one for .

$ mkdir foo
$ ls -l
total 2
drwxr-xr-x  2 user   wheel  512  4 oct 14:02 foo

Is it safe to always assume that the number of links above 2 corresponds to the number of subdirectories in this dir (.. links) ?

Eugene Yarmash
  • 2,433
  • 5
  • 34
  • 54

4 Answers4

2

You are correct to observe that all directories contain . and .., so if you subtract two from the output of

ls -la | grep '^d' | wc -l

you should get the number of directories in your current working directory.

MadHatter
  • 79,770
  • 20
  • 184
  • 232
2

this does not answer your question about ls -l, but I use tree -d for this, it works very nicely.

natxo asenjo
  • 5,739
  • 2
  • 26
  • 27
1

While generally you can only use symbolic links to directories, which will not affect the link count, there are some circumstances where hard-links are possible for directories (IIRC OSX's TimeMachine feature uses such links) so it might not always be guaranteed.

You would be safer passing a scan using ls and grep (or perhaps find) to the wc command to count the number of sub-directories actually present rather than trying to guess from the current directories link count.

David Spillett
  • 22,754
  • 45
  • 67
  • I don't understand - unless you use the -i flag to compare the results, ls won't find any duplicates. That being said, I've never encountered multiple hardlinks to directories (disregarding . and ..) and I'm highly surprised that some tool should use them by design. I wouldn't be surprised if standard tools such as find, ls -R and tar assume this property to hold. – reinierpost Oct 12 '10 at 08:20
0

I would use find

find ./foo -type d | wc -l

eventually with the -maxdepth option

marcoc
  • 748
  • 4
  • 10