du to just look at directories and sort by size

1.7k Views Asked by At

There are very long threads on this, I've read all that I could find, they don't answer my question.

The following is the best I can find to get a nicely formatted du listing inside a folder:

du -hsc $(ls -A) | sort -h

However, it's not what I want exactly as I want it to filter out / not show files in the top folder. I just want to get a summary of the directories (including .* directories) without the clutter of individual files. I think I would need to modify the ls but don't know how?

Even better would be to do the above, and additionally show a line of just the combined size of all files that are in the top level of this folder to show alongside all of the subfolder totals if that's possible?

3

There are 3 best solutions below

15
On BEST ANSWER

I don't see why you want to use ls here. A simple

old_setting=$(shopt -p dotglob)
shopt -s dotglob
du -hsc */
eval $old_setting

would be sufficient. The terminating slash is important, as this instructs bash to only create directory names, and you need to set dotglob to include dot-directories (except . and ..). In my code I have also carefully saved the old dotglob setting and restored it otherwise. You only need to do this if your code is part of a large script where some part of it may rely on the default value for dotglob.

Side note: A completely different approach would be to choose zsh instead of bash for your script. In zsh, you don't need to change any option, but just express in the pattern itself that you want to glob the dot-directories:

du -hsc */(D)  # This is for zsh only! 
5
On

(Mostly) repeated from comments:

You could just use -F in ls and then filter out the lines that don't end in /. eg du -hsc $(ls -AF) | sort -h | sed '\@/$@!d'

This will remove the total, and you can get that back easily with:

du -hsc $(ls -AF) | sort -h | sed '$p; \@/$@!d'
3
On

Without parsing the output of ls which is a terrible choice:

printf %s\\n .[^.]*/ ..[^.]/ ..[^.]*/ */ |
  xargs du -hsc 2>/dev/null |
    sort -k1h

If you need to support directories names with newline or special chars:

printf %s\\0 .[^.]*/ ..[^.]/ ..[^.]*/ */ |
  xargs -0 du -hsc0 2>/dev/null |
    sort -zk1h |
      xargs -0l