3

I have to count the total number of directories that are in the given directory (note that these are subdirectories).

I know how to count for files but am having trouble counting the directories for my script.

3
  • 3
    find <DirName> -type d | wc -l . this would include the current directory as well.
    – rahul
    Commented Apr 21, 2015 at 15:25
  • Directories just in the current directory, or directories in and below the current directory? Commented Apr 21, 2015 at 15:58
  • Just in the directory (not including the current working directory) I used the above format and then just subtracted 1
    – Yasuo
    Commented Apr 21, 2015 at 18:45

3 Answers 3

5

In a slightly robuster variation of @rahul's comment:

find . -type d -mindepth 1 -printf '1'  | wc -c

will print '1' for each directory in the current one that is not the current one (-mindepth 1), and then we count the 1s. This will cope with directory names that contain newlines.

4

If you put a / at the end of a wildcard pattern, the pattern will only match directories and symbolic links to directories. The following snippet therefore counts directories and symbolic links in the current directory.

set -- */ .*/
if ! [ -e "$1" ]; then shift; fi # handle the case when */ matches nothing
echo $(($# - 2)) # -2 for . and ..

In bash, you can simplify this to

shopt -s dotglob nullglob
dirs=(*/)
echo ${#dirs[@]}

If you don't want to include directories, use find. If none of the directories have a name that contains a newline, you can count the lines:

find . -name . -o -type d -print -prune | wc -l

To be fully robust, count slashes instead.

find . -name . -o -type d -print -prune | tr -dc / | wc -c
3

Counting directories in (only) the current directory:

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

Counting directories in the current directory and in all subdirectories contained within it:

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

You must log in to answer this question.

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