How to count all folder and sub folder in a directory recursive way

Solution 1:

To count all the directories including hidden ones in a tree rooted at the current directory . either

find . -type d -printf '\n' | wc -l

or

find . -type d -printf x | wc -c

(you can substitute any single character in place of x: if you choose a character that is special to the shell, make sure to quote or escape it). Using printf '\n' | wc -l or printf x | wc -c instead of passing a list of filenames to wc -l will ensure the count is correct even if there are directories whose names contain newlines.

Both commands include the starting directory . in the count - if you want to strictly count subdirectories then either subtract 1 or add -mindepth 1

find . -mindepth 1 -type d -printf '\n' | wc -l

or use ! -name . to exclude the . directory explicitly.

If you want to exclude hidden directories (including possible non-hidden subdirectories of hidden ones), then prune them ex.

find -mindepth 1 -type d \( -name '.*' -prune -o -printf x \) | wc -c

Alternatively, using the shell's recursive globbing to traverse the tree. Using zsh for example

dirs=( **/(ND/) )
print $#dirs

where (ND/) are glob qualifiers that make **/ match only directories and include hidden ("Dot") ones - omit the D if you want to count non-hidden directories only.

You can do something similar in bash:

shopt -s nullglob dotglob globstar
set -f -- **/
printf '%d\n' "$#"

however unlike zsh's / qualifier, the **/ glob pattern matches anything that looks like a directory - including symbolic links to directories.

Solution 2:

Try running ls -l -R | grep -c ^d in your terminal from the directory you want to know how many are inside of.

*** edit *** Use the below to scan with a variable path prompted to the user.

#!/bin/bash
echo "Please enter path to scan:"
read path
ls -l -R $path | grep -c ^d