Shell – How to list ALL directories according to their size? [without including the parent directory]

command linedisk-usagefindlsshell

I have a bunch of random folders, some of them are hidden (beginning with a period). I want to list all of them, sorted by their sizes.

I have something on the lines of this in mind:

ls -d -1 -a */ | xargs du -s | sort

But the ls ... part of it doesn't show hidden files. I know some questions have been asked before on the same topic, but the answers never include a way to include hidden files. Or if it does, it uses the long format, hence making the output incompatible with the rest of the command.

Best Answer

Parsing the output of ls is always problematic. You should always use a different tool if you mean to process the output automatically.

In your particular case, your command was failing -- not because of some missing or incompatible argument to ls -- but because of the glob you were sending it. You were asking ls to list all results including hidden ones with -a, but then you were promptly asking it to only list things that matched the */ glob pattern which does not match things beginning with. and anything ls might have done was restricted to things that matched the glob. You could have used .*/ as a second glob to match hidden directories as well, or you could have left the glob off entirely and just let ls do the work. However, you don't even need ls for this if you have a glob to match.

One solution would be to skip the ls entirely and just use shell globing:*

$ du -s */ .*/ | sort -n

Another way which might be overkill for this example but is very powerful in more complex situations would be to use find:*

$ find ./ -type d -maxdepth 1 -exec du -s {} + | sort -n

Explanation:

  • find ./ starts a find operation on the current directory. You could use another path if you like.
  • -type d finds only things that are directories
  • -maxdepth 1 tells it only to find directories in the current directory, not to recurse down to sub-directories.
  • -exec [command] [arguments] {} + works much like xargs, but find gets to do all the heavy lifting when it comes to quoting and escaping names. The {} bit gets replaced with the results from the find.
  • du -s you know

* Note that I used the -n operator for sort to get a numeric sorting which is more useful in than alphabetic in this case.