In Linux, the “du” (disk usage) command is used to show the size occupied by the files/directories including sub-directories. By default, the “du” command shows the sizes of directories in units of 1024 bytes (also known as “KiloBytes” or “K”).
This guide will provide multiple ways to sort the output of the “du” command by size and display the largest files or directories first. The supported content of this article is given below:
- Sorting Output in Human-Readable
- Sort Output in Descending Order
- Sort Output in Ascending Order
- Sort Output of Hidden Files with Total Size in Descending Order
- Limit the Amount of Time For Sorting Output
Sort Output in Human-Readable
The “du” command is used with “-h” options to display the sizes in “human-readable” format. It means the sizes will be shown in units of K (for Kilobyte), M (for Megabytes), G (for Gigabytes), or T (for Terabytes), depending on the size of the directory:
$ du -h
The output shows the sizes of all directories and subdirectories in a human-readable format.
Sort Output in Descending Order by Size (Largest to Smallest)
To sort the output in descending order by size, you can use the “sort” command in combination with the “du” command. Also, the “-hr” option makes the size of files and directories readable:
$ du -h | sort -hr
This will show the size of each file or directory in human-readable format and sort the output in descending order by size.
Sort Output in Ascending Order by Size
To sort the output in ascending order, users can use the “sort” command with the “-n” option. It sorts the output of numeric numbers in ascending order. To do so, execute the following command:
$ du -h | sort -n
The output shows that all files and directories have been sorted in ascending order.
Sort Output of Hidden Files With Total Size in Descending Order
You can use the “-a” option to show the sizes of all files and directories, including those that are hidden via the “h” option, and the “-c” option to show the total size of files:
$ du -ahc | sort -hr
This will show the sizes of all files and directories, including hidden ones, and display a total at the end, sorted in descending order by size.
Limit the Amount of Time For Sorting Output
The “du” command can take some time to run, especially on large directories or filesystems, so you may want to use the “timeout” command to limit the amount of time it runs:
$ timeout 60 du -ahc | sort -hr
This will run the “du” command for a maximum of 60 seconds before exiting.
Note: For more details, read our extensive tutorial on the du command.
Conclusion
In Linux, you can sort output with the combination of “du” and “sort” commands. Using the “h” option, they display the output in the human-readable format in units of KBs, MBs, GBs, or TBs, depending on the directory size. This guide has explained all possible ways to sort the output of a du command.