Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
Sometimes, we want to find the total size of all files in a directory and all its subdirectories. One easy way to do this is by using the du command.
In this short tutorial, we’ll look at how to use du to calculate the total size of files in a directory.
Let’s say we have the following directory:
$ ls
Zoom.pkg jdk-15.0.2_osx-x64_bin.dmg
etc pdfs
googlechrome.dmg photos
To get the total size of all the files in and under this directory, we can use du:
$ du -s
1278490188 .
The -s argument provides the summary of all space used for the given directory. We can also add -h to make it a friendly number (as opposed to bytes):
$ du -sh
1.2G .
With most versions of du, we can tell it to ignore certain files. Let’s add –exclude to our du command along with a shell pattern to ignore all the .dmg files:
$ du -sh --exclude='*.dmg'
466M .
This is the summary of the space used by the files and subdirectories in our downloads folder, not counting any .dmg files. On some systems, the ignore command is a -I argument followed by the pattern:
% du -sh -I "*.dmg"
466M .
Now we have an idea of how much space the files are taking up. Next, let’s locate a specific file or directory that is taking up a lot of space. If we add -d 1 to our command, we can calculate directory sizes at a specific depth:
$ du -d 1 -h
662M ./etc
12M ./pdfs
231M ./photos
1.2G .
We took out the -s argument and replaced it with our -d argument to get our result. By using the -d argument, we can find which directory is taking up a lot of space. In this case, etc/ seems to be the main offender.
To dig deeper, we could use -d 2 or -d 3, and so on, to show files multiple levels deep. Alternatively, we could cd into a particular directory and run our du command again to find the largest subdirectory or file lower down the directory structure.
In this article, we looked at an easy way to find the total size of all files in a directory.
We also learned how to find which subdirectories are taking up all the space.