Command to delete directories whose contents are less than a given size

directoryfind

I'm working in a directory ~/foo which has subdirectories

~/foo/alpha
~/foo/beta
~/foo/epsilon
~/foo/gamma

I would like to issue a command that checks the total size under each "level 1" subdirectory of ~/foo and deletes the directory along with its contents if the size is under a given amount.

So, say I'd like to delete the directories whose contents have less than 50K. Issuing $ du -sh */ returns

8.0K alpha/
114M beta/
20K  epsilon/
1.2G gamma/

I'd like my command to delete ~/alpha and ~/epsilon along with their contents. Is there such a command? I suspect this can be done with find somehow but I'm not quite sure how.

Best Answer

With GNU find and GNU coreutils, and assuming your directories don't have newlines in their names:

find ~/foo -mindepth 1 -maxdepth 1 -type d -exec du -ks {} + | awk '$1 <= 50' | cut -f 2-

This will list directories with total contents smaller than 50K. If you're happy with the results and you want to delete them, add | xargs -d \\n rm -rf to the end of the command line.

Related Question