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 -rhExplanation:
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 theducommand as input to thesortcommand.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.