Du Command - Disk Usage Utility | Online Free DevTools by Hexmos

Master the du command for disk usage analysis. Learn to sort files by size, show human-readable disk space, and identify largest directories with this essential Linux utility.

Du Command Examples

The du command (disk usage) is a fundamental Linux utility used to estimate file space usage of directories and files. It's invaluable for system administrators and developers to understand storage consumption and optimize disk space. Below are common usage examples of the du command.

Sort Directories by Size

To sort directories and files by their size in descending order, you can pipe the output of du to the sort command. The -k flag specifies the key for sorting (in this case, the size), and -rn sorts numerically in reverse order.

# To sort directories/files by size:
du -sk *| sort -rn

Human-Readable Cumulative Size

Displaying disk usage in human-readable format (e.g., KB, MB, GB) is crucial for easy understanding. The -s flag summarizes the total size for each argument, and -h makes the output human-readable.

# To show cumulative human-readable size:
du -sh

By default, du reports the size of the symlink itself, not the file it points to. Use the -L flag to dereference symlinks and report the size of the target files.

# To show cumulative human-readable size and dereference symlinks:
du -shL

Apparent Size vs. Disk Usage

du typically reports disk usage, which can differ from the actual file size due to block allocation. The --apparent-size option shows the apparent size, which is useful for understanding the true size of files, especially sparse files.

# Show apparent size instead of disk usage (so sparse files will show greater
# than zero):
du -h --apparent-size

Human-Readable Sorting

Combining human-readable output with sorting provides a very practical way to identify large files and directories. This command sorts the output of du -sh * in reverse human-readable order.

# To sort directories/files by size (human-readable):
du -sh * | sort -rh 

List Largest Files and Folders

To quickly find the top N largest files and folders, you can use du -ma (-m for megabytes, -a for all files) and then pipe the output to sort -nr and head -n 20 to get the top 20.

# To list the 20 largest files and folders under the current working directory:
du -ma | sort -nr | head -n 20

Further Resources