counting number of directories in a specific directory

后端 未结 15 2177
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 21:06

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         


        
15条回答
  •  天涯浪人
    2020-12-22 21:25

    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:

    1. folder's own self-referential ./ entry, and
    2. folder's parent's link to folder

提交回复
热议问题