2

I want to use the du command so I can find the folders on my system that are bigger than a certain size.

The problem with du are the results I get.

For example, I get all theses folders as results:

~/Downloads/MyFiles/MyPictures/Folder1/
~/Downloads/MyFiles/MyPictures/
~/Downloads/MyFiles/ 
~/Downloads/

When I only want to have :

~/Downloads/MyFiles/MyPictures/Folder1/

How can I do that with du or any other command?

1
  • So, you only count a folder if it has no sub folders or sub folders are ok if they are small? It’s not a direct answer, but ncdu or Daisy Disk search rapidly / interactively once a map is done – bmike Aug 2 '19 at 11:32
1

du alone won't help here, but you can combine du with find to accomplish this:

find . -type d -exec sh -c '(ls -p "{}" | grep -q /) || du "{}"' \;

What this does is the following:

  • find . -type d -exec ... \; finds all directories and executes the part in ... for each of them (with {} getting replaced by the path of the directory)
  • sh -c '...' executes the ... part in a subshell (because -exec only can execute a binary and doesn't itself know about shell syntax)
  • (ls -p "{}" | grep -q /) lists all entries within the directory with a / appended if an entry itself is a directory, and then greps silently for lines containing /. We are only interested in the return code of grep here so if you want to manually check what it does run (ls -p "DIR" | grep -q /); echo $? with various DIRs to see the difference between directories containing sub-directories and directories which don't
  • || du "{}" gets executed only if the previous part ((...)) did not find any matches (meaning we are in a directory without further directories)

PS: Tip of the hat to https://stackoverflow.com/questions/4269798/use-gnu-find-to-show-only-the-leaf-directories for the essential details.

1
  • This is one to bookmark for advanced shell scripting. Well done, indeed! – bmike Aug 4 '19 at 20:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .