Sort du Command Output by File/Folder Size (Linux, macOS, BSD)

TL;DR: To sort du command’s output in ascending order of the file and/or directory sizes, we can pipe its output to sort -h. To sort in descending order, pipe it to sort -hr. This should work in most Unix-based or Unix-like operating systems (Linux, BSD, macOS):

$ du [OPTION] [FILE] | sort -h # Ascending order of sizes
$ du [OPTION] [FILE] | sort -hr # Descending order of sizes

The du command displays the disk usage statistics (estimated file space usage) of the files or directories (recursively) passed to it as arguments. With a couple of options, we can get a decent output:

# Get file and folder sizes present in the current directory
$ du -ah -d 1 2>/dev/null
1.8G    ./.vscode-server
39M     ./airflow
5.6G    ./.pyenv
23G     ./data
4.0K    ./.gcloud
36K     ./snap
14G     ./.cache
256K    ./.mongodb
4.0K    ./.gitconfig
44K     ./.python_history
214M    ./.local
4.0K    ./tmp
48K     ./.bash_history
...

The options used are:

  • -a, --all – Displays usage stats for files too, not just directories.
  • -h, --human-readable – Prints sizes in human-readable format (e.g., 1K, 234M, 2G).
  • -d, --max-depth=N – Process stats for N levels in the directory (argument) hierarchy.
  • 2>/dev/null – Any directory/file that can’t be processed (due to permission error for instance) will throw an error. With this, we pipe errors to /dev/null.

Note: In the command above, we don’t pass any file or directory as an argument to the command. This makes it default to the current working directory which in this case is HOME.

As you can see, the output above is listed in random order (not sorted on size or file/folder names). To sort the output above by the sizes that you see in ascending order, we can pipe the output to the sort command:

$ du -ah -d 1 2>/dev/null | sort -h
4.0K    ./.gcloud
4.0K    ./.gitconfig
4.0K    ./tmp
36K     ./snap
44K     ./.python_history
48K     ./.bash_history
256K    ./.mongodb
39M     ./airflow
214M    ./.local
1.8G    ./.vscode-server
5.6G    ./.pyenv
14G     ./.cache
23G     ./data
...

To sort in reverse (descending) order, you can use the -r option with sort -h, i.e., sort -hr. Here’s an explanation of the options:

  • -h, --human-numeric-sort – Compare human readable numbers (eg, 2K, 1G)
  • -r, --reverse – Reverse the result of comparisons.
$ du -ah -d 1 2>/dev/null | sort -hr
46G     .
23G     ./data
14G     ./.cache
5.6G    ./.pyenv
1.8G    ./.vscode-server
214M    ./.local
39M     ./airflow
256K    ./.mongodb
...

Leave a Reply

Your email address will not be published.