1

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

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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