How to count the number of folders in a specific directory. I am using the following command, but it always provides an extra one.
find /directory/ -maxdept
Run stat -c %h folder
and subtract 2 from the result. This employs only a single subprocess as opposed to the 2 (or even 3) required by most of the other solutions here (typically find
plus wc
).
Using sh/bash:
cnt=$((`stat -c %h folder` - 2))
echo $cnt # 'echo' is a sh/bash builtin, not an additional process
Using csh/tcsh:
@ cnt = `stat -c %h folder` - 2
echo $cnt # 'echo' is a csh/tcsh builtin, not an additional process
Explanation: stat -c %h folder
prints the number of hardlinks to folder, and each subfolder under folder contains a ../ entry which is a hardlink back to folder. You must subtract 2 because there are two additional hardlinks in the count: