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) ?

2
  • why not use something like ls -d1 */ | wc -l That'll also take into account links, if thats what you want.
    – Sirex
    Oct 4, 2010 at 11:35
  • @Sirex: it's just curiosity, really. Oct 4, 2010 at 13:09

4 Answers 4

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.

1
  • 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. Oct 12, 2010 at 8:20
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.

2

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

0

I would use find

find ./foo -type d | wc -l

eventually with the -maxdepth option

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .