How to use the du command in Linux
The du command is used to find out how much system memory is used by different directories or subdirectories. The general syntax of the du command in Linux is:
There are different options that can be used with the du command for different purposes:
Options | Purposes |
---|---|
h | To display the units |
a | To display the disk space utilized by all the files available of the specified directory |
s | To display the total of each directory |
c | It combines all the sizes of the files and displays them separately in the section of the total |
–apparent-size | It displays the absolute size of the files in the directory |
–max-depth | It is used to specify the command to which folder go within the directory |
–exclude | It is used to exclude some specified files |
–time | It displays the time of the last modification made in the file |
Before using these options, we will display the disk size used by the directories in the Home directory using the command:
In the output, the sizes are displayed but without the units, it is difficult for us to recognize whether these are in GBs, MBs, or in KBs, to display the sizes with units, we execute the above command using the “-h” option:
The sizes utilized by the files in the directory are understandable as the units are mentioned with them; to display all the files present in any directory or sub-directory, we can use the “-a” flag:
In the above output, if we want to display the summary of the size of “new_directory” only we can replace the “-s” flag with the “-a” flag in the options:
To display the size of all files of the directory of Documents, and display their combined result under the title of “Total” we use the “-c” flag:
If we need to display the apparent size of the files available in the directory, we will use the option of the “–apparent-size”:
Similarly, we can limit the terminal to go to the specified subfolders by using the option of “–max-depth”, for example, we specify “1” to go to the only first subfolders:
We can see from the output, the size has been calculated and displayed only for the first folder, now if we want to calculate and display up to the first two folders, run the command:
We can exclude files by using the option of “–exclude”. For example, we can exclude all the hidden files from the home directory, by using the “./.” for hidden files:
The last option we are discussing in this write-up is the time option which is used to display the changes made in the last file:
Conclusion
The du command is very helpful in managing the disk space as it tells how much space has been occupied by the files and packages, so we can calculate how much space is left free in the disk for new files and packages. In this write-up, we have discussed the different ways of using the du command with its various options.