How can I sort `du -h` output by folder size?

0
0
Asked By MellowCedar42 On

I use `du -h --max-depth=1` in the command line to check the sizes of directories. Is there a way to sort the results from smallest to largest, or from largest to smallest?

3 Answers

Answered By QuietFalcon18 On

`du` itself generally doesn’t sort the output, so combining it with the separate `sort` command is the portable approach. For example: `du --human-readable --max-depth=1 /some/path | sort -h`. Add `-r` to reverse the order.

MellowCedar42 -

That explanation helps—using a pipe to connect small tools makes sense. The simpler command is exactly what I needed.

Answered By SilverPebble29 On

On systems whose version of GNU `du` supports it, `du -h --max-depth=1 --sort=size` may sort by size directly. However, that option isn’t available everywhere, including some Debian setups, so `du -h --max-depth=1 | sort -h` is the safer option.

Answered By BrightMango7 On

Pipe the output into `sort`, using its human-readable size option: `du -h --max-depth=1 | sort -h` sorts from smallest to largest, while `du -h --max-depth=1 | sort -hr` sorts from largest to smallest. The `-h` option makes `sort` understand values such as KiB, MiB, and GiB instead of treating them as ordinary text.

MellowCedar42 -

Thanks! I’m using Debian, where `du --sort=size` doesn’t seem to be available, but the `sort -h` pipeline works perfectly.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.