List directories by size

To list directories by size in Linux, displaying the size in human-readable units like MB or GB, the du command is used in conjunction with sort.

The following command lists the sizes of subdirectories within the current directory, sorted from largest to smallest, with sizes displayed in human-readable format:

du -h --max-depth=1 . | sort -rh

Explanation:

  • du -h --max-depth=1 .:
    • du: The “disk usage” command, used to estimate file space usage.
    • -h: Displays sizes in a human-readable format (e.g., K, M, G for kilobytes, megabytes, gigabytes).
    • --max-depth=1: Limits the output to only the top-level directories and files within the current directory, preventing a recursive scan of all subdirectories.
    • .: Specifies the current directory as the target.
  • | sort -rh:
    • |: Pipes the output of the du command as input to the sort command.
    • sort: Sorts the lines of text files or standard input.
    • -r: Sorts in reverse order (descending), placing the largest directories at the top.
    • -h: Sorts by human-readable numbers, ensuring that sizes like “1.2G” are correctly compared to “800M”.

To check the size of a specific directory and its contents, you can use:

du -sh /path/to/directory
  • -s: Summarizes the total size of the specified directory, including all its subdirectories and files. 
  • /path/to/directory: Replace this with the actual path to the directory you want to check. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

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