Linux - List and sort folders by size

By xngo on March 23, 2020

In Linux, there are multiple ways to list and sort directories by size. In the example below, I will use du to list directories size, sort to sort directories by size and numfmt to format numbers into human readable format.

du

Here, the command du is used to list the directories with their sizes.

du -ch --max-depth=1
#    36M  ./openra
#    28K  ./xtra-work-selenium-00-cache-pip
#    32K  ./xtra-work-selenium-01-pip
#    232K ./scripts.old
#    36M  .
#    36M  total
  • c: Print the total.
  • h: Print sizes in human readable format (e.g., 1K 234M 2G)
  • --max-depth=1: Print the total of each first level directory.

sort

Since we want to sort the directories by size in ascending order, we have to omit the human readable option from the du command so that we can pass the size numbers to sort command.

du -c --max-depth=1 | sort -k1,1n
#    28       ./xtra-work-selenium-00-cache-pip
#    32       ./xtra-work-selenium-01-pip
#    232    ./scripts.old
#    36548    ./openra
#    36860    .
#    36860    total
  • sort -k1,1n: Sort the first column numerically.

numfmt

Finally, we use numfmt to format the numbers into human readable format.

du -c --max-depth=1  \
    | sort -k1,1n  \
    | numfmt --field=1 --from-unit=1024 --to=iec-i  --format='%10f' --suffix B
 
#      28Ki ./xtra-work-selenium-00-cache-pip
#      32Ki ./xtra-work-selenium-01-pip
#     232Ki ./scripts.old
#      36Mi ./openra
#      36Mi .
#      36Mi total
#    
  • --field=1: Format the 1st column.
  • --from-unit=1024: Since du returns values in kilobytes, then we have to set the starting point to 1024.
  • --to=iec-i: Auto-scale numbers according to the International Electrotechnical Commission (IEC) standard.
  • --format='%10f': Pad to 10 characters, left-aligned.
  • --suffix B: Add B at the end.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.