number of folders in a directory (recursive)
This will find the number of non-hidden directories in the current working directory:
ls -l | grep "^d" | wc -l
EDIT:
To make this recursive, use the -R
option to ls -l
:
ls -lR | grep "^d" | wc -l
In the GNU land:
find . -mindepth 1 -maxdepth 1 -type d -printf . | wc -c
elsewhere
find . -type d ! -name . -printf . -prune | wc -c
In bash:
shopt -s dotglob
count=0
for dir in *; do
test -d "$dir" || continue
test . = "$dir" && continue
test .. = "$dir" && continue
((count++))
done
echo $count
echo $(($(find -type d | wc -l) - 1))
is one way (subtract 1 from the wc -l to remove the current dir). You can tweak the options to find to find different things.
echo $(($(find -type d -not -path '*/\.*' | wc -l) - 1))
- to exclude the hidden dirs
As I mentioned in the comments, the heart of this expression is really find -type d
, which finds all directories.
Note this finds all subfolders as well - you can control the depth using the -maxdepth
flag.