Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to define alias for a group of commands counting recursively and displaying the number of all sub-directories encountered for any working directory (including ones with invisible file names). So far what I have done is:

ls -R | wc -l

But it does not display the hidden files number. So I tried this command:

ls -l | grep ^d | wc -l

But I am not sure whether it is the right command or not?

share|improve this question
up vote 1 down vote accepted

You should never parse the output of ls. See some explanations here:

As others recommended, use find instead. And the best way (even when you have directory names that contain newlines or other types of white space) would be:

alias countdir='find . -type d -print0 | tr -dc "\\0" | wc -c'

See man find, man tr, man wc for more info.

share|improve this answer

Is find . -type d|wc -l a solution?

share|improve this answer

I'd recommend using find (man page) to do the searching. As an example,

find . -maxdepth 1 -type d | wc -l

will print the number of all directories in the current working directory.

The -maxdepth option controls how far find will descend into the directories. With a value of 1, it will just use the current directory and list its subdirectories. With 2, it will list the subdirectories' subdirectories, too, and so on.

This has just a single, small drawback: find includes . (the current working directory) in its listing, thus the number returned by wc -l will be off by one.

share|improve this answer

Your Answer


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.