du command is a short form of “disk usage” is used to get details of used disk space by given files or directories. Generally, it is used to find out the large size files which occupies more disk space. In this article we will cover how to use the du command in Linux.
How to Use the du command
Below is the basic syntax for the
du [OPTIONS]... FILE...
If you will run the du command without giving
FILE name it will display the disk usage of the current working directory. When pass a directory path as
FILE, the du command displays the disk usage summary for each files and subdirectories.
You can also pass multiple files and directories to the
du command as arguments:
du ~/Documents ~/Pictures ~/.zshrc
If the user have not proper permissions for a file or directory which passed in du command, it will show error like “du: cannot read directory”. You should run the command with sudo.
There are many options of
du command, here most frequently used are discussed below:
-a option you can get the disk space usage for each file within the directory.
du -a ~/Documents
Generally, we need to get space occupied by given directory in a human-readable format. You can use the
-h option for that.
For example, to get the total size of the
/var/lib and all of its subdirectories, you would run the following command:
sudo du -h /var
We are using
sudo because most of the files and directories inside the
/var/lib directory are owned by the root user and are not readable by the regular users. The output will look something like this:
-s option to get the total size of the specified directory and not for subdirectories:
sudo du -sh /var
-c option tells du to report a grand total. This is useful when you want to get the combined size of two or more directories.
sudo du -csh /var/log /var/lib
--max-depth option to display the disk usage of the n-level subdirectories.
For example, to get a report about the first-level directories you would use:
sudo du -h --max-depth=1 /var/lib
Using du with Other Commands
You can use the
du command with the combination of the other commands using pipes.
For example, we will find the
3 largest directories inside the
/var directory. For that we need to pass the output of du to the sort command for sorting the directories by their size then pipe the output to the
head command to print only the
sudo du -h /var/ | sort -rh | head -3
You learned how to use the
du command in Linux. The
du command gives you estimate of disk space used by given file or directories while df command show the information about the disk usage of the mounted file systems.
If you have any questions or feedback, please leave a comment below.