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.
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.
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
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
find <DirName> -type d | wc -l
. this would include the current directory as well.