How to get the total number of subdirectories count in Linux?

after doing
mkdir -p A/B/C
how can i get the total count of subdirectories? which is three in this case

Try the find command with -type d to list dirs only. For example, in mkdir A/B/C search path starts with A/, then one could write:

search="A/"
find "$search"  -type d  | grep -vw "^${search}$" | wc -l
  1. The find command returns all sub-dirs in the given path, which is set by the shell variable named $search
  2. The grep command will exclude search-based paths. If you want that too, remove the grep command (e.g. find "$search" -type d | wc -l)
  3. The wc command counts line, thus returning sub-dir count inside the $search path.

The ls method is unreliable and hence should be avoided when counting sub-dirs.

1 Like

I think it’s just easier to count the lines and +1 the start folder to the resulting count:

find A -type d -print | wc -l

-print might not be needed but I play it safe and for clarity.

1 Like