Finding empty directories UNIX

后端 未结 12 630
心在旅途
心在旅途 2020-12-07 14:11

I need to find empty directories for a given list of directories. Some directories have directories inside it.

If inside directories are also empty I can say main di

12条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 14:56

    This recursive function would seem to do the trick:

    # Bash
    findempty() {
        find ${1:-.} -mindepth 1 -maxdepth 1 -type d | while read -r dir
        do
            if [[ -z "$(find "$dir" -mindepth 1 -type f)" ]] >/dev/null
            then
                findempty "$dir"
                echo "$dir"
            fi
        done
    }
    

    Given this example directory structure:

        .
        |-- dir1/
        |-- dir2/
        |   `-- dirB/
        |-- dir3/
        |   `-- dirC/
        |       `-- file5
        |-- dir4/
        |   |-- dirD/
        |   `-- file4
        `-- dir5/
            `-- dirE/
                `-- dir_V/
    

    The result of running that function would be:

        ./dir1
        ./dir5/dirE/dir_V
        ./dir5/dirE
        ./dir5
        ./dir2/dirB
        ./dir2
    

    which misses /dir4/dirD. If you move the recursive call findempty "$dir" after the fi, the function will include that directory in its results.

提交回复
热议问题