4

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.

12

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.

  • 3
    @BrianFitzpatrick There is also ncdu that can be useful occasionally. – lcd047 Jul 6 '15 at 6:01
-1

First answer work well but not with dir name who contain spaces. (corrected logic because this was anything 50Kb or over)

#RESULTTODELETE=$(find ~/foo -mindepth 1 -maxdepth 1 -type d -exec du -ks {} + | awk '$1 <= 50' | cut -f 2-); RESULTTODELETE2=$(echo "$RESULTTODELETE" | sed 's, ,\\ ,g'); echo "$RESULTTODELETE2" | xargs rm -rf

Will work with :

~/f oo/a lpha
~/fo o/be ta
~/f o o/ep silon
~/foo/gamma
  • This looks extremely complex and brittle. Usually the recommended approach is to handle everything related to file name handling inside the -exec; spaces are not the only problematic character, mind you (newlines are another common corner case, though it's less often encountered in reality). – tripleee Apr 16 '17 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.