Pure bash solution:
shopt -s nullglob dirs=( /path/to/directory/*/ ) echo "There are ${#dirs[@]} (non-hidden) directories"
If you also want to count hidden directories:
shopt -s nullglob dotglob dirs=( /path/to/directory/*/ ) echo "There are ${#dirs[@]} directories (including hidden ones)"
Please note that this will also read directory links. If you do not want this, it is a little more complicated with this method.
Using find :
find /path/to/directory -type d \! -name . -prune -exec printf x \; | wc -c
The trick is to output x to stdout every time a directory is found, then use wc to count the number of characters. This will count the number of all directories (including hidden ones), excluding links.
The methods presented here are safe for funny characters that can appear in file names (spaces, newlines, globe characters, etc.).
gniourf_gniourf May 27 '16 at 11:02 2016-05-27 11:02
source share