Finding empty directories UNIX

后端 未结 12 624
心在旅途
心在旅途 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:29

    find . -type d -empty

    finds and lists empty directories and sub-directories in the current tree. E.g. resulting list of empty dirs and subdirs:

    ./2047
    ./2032
    ./2049
    ./2063
    ./NRCP26LUCcct1/2039
    ./NRCP26LUCcct1/2054
    ./NRCP26LUCcct1/2075
    ./NRCP26LUCcct1/2070
    

    No operation is made on the directories. They are simply listed. This works for me.

    0 讨论(0)
  • 2020-12-07 14:33

    It depends a little on what you want to do with the empty directories. I use the command below when I wish to delete all empty directories within a tree, say test directory.

    find test -depth -empty -delete
    

    One thing to notice about the command above is that it will also remove empty files, so use the -type d option to avoid that.

    find test -depth -type d -empty -delete
    

    Drop -delete to see the files and directories matched.

    If your definition of an empty directory tree is that it contains no files then you be able to stick something together based on whether find test -type f returns anything.

    find is a great utility, and RTFM early and often to really understand how much it can do :-)

    0 讨论(0)
  • 2020-12-07 14:34

    The following command returns 1 if a directory is empty (or does not exists) and 0 otherwise (so it is possible to invert the return code with ! in a shell script):

    find $dir -type d -prune -empty -exec false {} +
    
    0 讨论(0)
  • 2020-12-07 14:38

    a simple approach would be,

    $ [ "$(ls -A /path/to/direcory)" ] && echo "not empty" || echo "its empty"
    

    also,

    if [ "$(ls -A /path/to/direcory)" ]; then
       echo "its not empty"
    else 
       echo "empty directory"
    
    0 讨论(0)
  • Check whether find <dir> -type f outputs anything. Here's an example:

    for dir in A B C; do
        [ -z "`find $dir -type f`" ] && echo "$dir is empty"
    done
    
    0 讨论(0)
  • 2020-12-07 14:40

    You can use the following command:

    find . -type d -empty
    
    0 讨论(0)
提交回复
热议问题