Using the du Command in the Linux Command Line
The du (disk usage) command in Linux is a powerful tool for checking the space used by files and directories. This article will cover some common uses of the du command, including examples with the -k and -h options, and how to find which files are filling up your filesystem.Basic Usage
The basic syntax of the du command is:
Code:
du [options] [file or directory]
Using the -k Option
The -k option displays the disk usage in kilobytes.Example:
Code:
du -k /path/to/directory
This command will show the disk usage of each file and directory within /path/to/directory in kilobytes.
Using the -h (Human-Readable) Option
The -h option makes the output more readable by using units like K (kilobytes), M (megabytes), and G (gigabytes).Example:
Code:
du -h /path/to/directory
This command will display the disk usage in a human-readable format.
Finding Which Files Are Filling Up the Filesystem
To find out which files are taking up the most space, you can use the du command in combination with other commands like sort and head.Example:
Code:
du -ah /path/to/directory | sort -rh | head -n 10
This command will display the top 10 largest files and directories within /path/to/directory.
Difference Between du -sh * and du -sh directory
The -s option provides a summary of the total disk usage, and the * wildcard includes all files and directories in the current directory.Example:
Code:
du -sh *
This command will show the total disk usage of each file and directory in the current directory.
Example:
Code:
du -sh /path/to/directory
This command will show the total disk usage of /path/to/directory as a whole.
Drilling Down Through the Filesystem
Sometimes, you need to drill down through the filesystem to find which files are taking up all the space. You can do this by running the du command on subdirectories.Example:
Code:
du -sh /path/to/directory/*
This command will show the disk usage of each subdirectory within /path/to/directory. You can then navigate into the largest subdirectory and repeat the process until you find the files consuming the most space.
Additional Tips
- Exclude Certain Files or Directories: You can exclude specific files or directories from the du output using the --exclude option.
Code:
du -ah --exclude="*.log" /path/to/directory
This command will exclude all .log files from the disk usage report.
- Summarize Disk Usage for Multiple Directories: You can summarize the disk usage for multiple directories by listing them.
Code:
du -sh /path/to/directory1 /path/to/directory2
This command will show the total disk usage for both /path/to/directory1 and /path/to/directory2.