Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

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

4 Answers 4

up vote 1 down vote accepted

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.

share|improve this answer
    
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 8:20

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.

share|improve this answer

I would use find

find ./foo -type d | wc -l

eventually with the -maxdepth option

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.