10 Useful ‘du’ (Disk Usage) Commands to Find Disk Usage of Files and Directories


Introduction

In the world of Linux and Unix-like systems, managing disk space efficiently is a crucial skill. One of the most powerful tools for this task is the ‘du’ command, which stands for Disk Usage. This article aims to guide beginners and intermediate users through 10 practical and easy-to-understand ‘du’ commands. These commands help you find out how much space files and directories are taking up on your hard drive, which is essential for system maintenance and managing resources.


1. Basic ‘du’ Command

The simplest way to use the ‘du’ command is without any options. Just type du in the terminal, and it will display the disk usage of directories and subdirectories in the current working directory. The output is in kilobytes.

du

2. Display Disk Usage in Human-Readable Form

To make the output more understandable, use the -h option. This command displays sizes in B (bytes), K (kilobytes), M (megabytes), and so on, making it easier to read.

du -h

3. Summarize Disk Usage of Each File

If you want a summary of each file rather than a long list, use the -a option with du. It lists the disk usage of all files and directories.

du -a

4. Find Disk Usage of Specific Directory

To check the disk usage of a specific directory, simply add the directory name after the command. For example, to check the usage of the /var directory:

du /var

5. Display Only Total Size

Sometimes, you might only want to know the total size of a directory. Use the -s option to get a summary without the detailed list.

du -sh /var

6. Exclude Certain Files

You can exclude files of a certain type using the --exclude option. For instance, to exclude all .jpg files:

du -h --exclude='*.jpg'

7. Maximum Depth of Display

To limit the depth of directories, use the --max-depth option. For example, to display only the first two levels:

du -h --max-depth=2

8. Compare Disk Usage

Use the --time option to compare the disk usage at different times. This command shows when the contents of the directory were last modified.

du -h --time

9. Find the Largest Files and Directories

Sorting the output to find the largest files and directories can be done using a combination of du and sort commands. This helps in identifying the files taking up the most space.

du -ah | sort -nr | head

10. Export Output to a File

For record-keeping or further analysis, you can redirect the output of du to a file using the > operator.

du -h > disk_usage.txt

Conclusion

Understanding and using the ‘du’ command is a fundamental skill for system administrators and regular users alike. By mastering these 10 commands, you’ll be better equipped to manage your system’s disk space effectively. Remember, regular monitoring of disk usage can prevent many common problems associated with limited storage space.


Leave a Comment