I'd like to sort all the directories/files in a specific directory based on their size (using du -sh "name").

I need to apply this command to all directories in my location, then sort them based on this result. How can I do that ?


With GNU sort and GNU du (which it appears you have, since you state you are using du's -h option):

du -sh -- *  | sort -rh  # Files and directories, or
du -sh -- */ | sort -rh  # Directories only

The output looks something like this:

22G     foo/
21G     bar/
5.4G    baz/
2.1G    qux/
1021M   wibble/
4.0K    wobble/
  • Note that if a file is hard linked in two or more directories, then the sizes of each directory reported by du depends on the order of the directories on the command line. Also, -h is available on other du implementations than GNU. – Kusalananda Apr 2 at 12:24

Sorting by block sizes and then turn that into human readable:

du -sk * | sort -nr | cut -f2 | xargs du -sh
  • 1
    This fails if the directory names contain whitespace. – Marco Dec 23 '13 at 9:59

This is an improved version based on jabalv's answer. It works with a GNU as well as a BSD userland.

IFS='\n' du -sk -- * | sort -n | cut -f2 |
while read line ; do
  xargs du -sh "$line"

sample output:

4.0K  games
2.7M  local
6.7M  lib32
19M   sbin
152M  src
177M  include
321M  bin
2.2G  share
2.9G  lib

To reverse the sort order and list the largest files and directories first, use sort -nr.


This command should work:

sudo du -sh $(sudo ls) | sort -h

  • 3
    Can you explain the need for each sudo and why you're using ls? Note that this would break for anything containing spaces. – Kusalananda Apr 2 at 12:25
  • @Kusalananda there is no need for each sudo. I wrote that because sometimes I was denied access to run this command. I use ls to list all the directories and use them as input to the du command. But yes, you are absolutely correct, this would definitely break for directories with whitespaces. – Faizan Apr 3 at 6:47

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.