For counting the number of non-hidden directories (in the current directory), using bash
:
shopt -s nullglob
set -- */
printf 'There are %d non-hidden subdirectories in %s\n' "$#" "$PWD"
To include the count of hidden directories:
shopt -s dotglob nullglob
set -- */
printf 'There are %d subdirectories in %s\n' "$#" "$PWD"
What these pieces of code do is to expand the pattern */
and to count the number of names that the pattern expands to. The pattern, since it ends with a slash, will only expand to directory names (or to names of symbolic links to directories).
The directory names will be assigned to the positional parameters, $1
, $2
etc. using set
, and the number of these parameters is kept in $#
by the shell (so there's no need to actually loop over them to count them).
If you feel more comfortable with bash
arrays:
shopt -s dotglob nullglob
dirs=( */ )
printf 'There are %d subdirectories in %s\n' "${#dirs[@]}" "$PWD"
This is essentially the same thing, except it uses a named array instead of the positional parameters.
The dotglob
shell option, in bash
, will make *
match hidden names as well as non-hidden names. The nullglob
shell option will make non-matching patterns expand to nothing.
Related: