Disk usage: How to only show max depth folders?
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?
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 ofgrep
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.