counting number of directories in a specific directory

后端 未结 15 2195
被撕碎了的回忆
被撕碎了的回忆 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:37

    A pure bash solution:

    shopt -s nullglob
    dirs=( /path/to/directory/*/ )
    echo "There are ${#dirs[@]} (non-hidden) directories"
    

    If you also want to count the hidden directories:

    shopt -s nullglob dotglob
    dirs=( /path/to/directory/*/ )
    echo "There are ${#dirs[@]} directories (including hidden ones)"
    

    Note that this will also count links to directories. If you don't want that, it's a bit more difficult with this method.


    Using find:

    find /path/to/directory -type d \! -name . -prune -exec printf x \; | wc -c
    

    The trick is to output an x to stdout each time a directory is found, and 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 all safe wrt to funny characters that can appear in file names (spaces, newlines, glob characters, etc.).

提交回复
热议问题