How to Get the Size of a Directory in Linux⚓
This will be a quick article on how to obtain the size of a directory, regardless of which flavor of Linux is being run.
Getting the Size of a Directory⚓
du command displays the amount of file space used by the specified files or directories. If the specified path is a directory,
du summarizes disk usage of each subdirectory in that directory. If no path is specified,
du reports the disk usage of the current working directory.
When invoked without any options,
du displays the disk usage of the given directory and each of its subdirectories in bytes.
Typically, you would want to display the space occupied by the directory in a human-readable format. For example, to get the total size of the
/var directory, you would run the following command:
The output will look something like this:
Let’s explain the command and its arguments:
- The command starts with
sudobecause most of the files and directories inside the
/vardirectory are owned by the root user and are not readable by the regular users. If you omit
ducommand will print “du: cannot read directory”.
s- Display only the total size of the specified directory, do not display file size totals for subdirectories.
h- Print sizes in a human-readable format (
/var- The path to the directory you want to get the size.
What if you want to display the disk usage of the first-level subdirectories? You have two options. The first one is to use the asterisk symbol (
*) as shown below, which means “match everything that doesn’t start with a period (
-c option tells
du to print a grand total of all sizes:
Another way to get a report about the disk usage of the first-level subdirectories is to use the
By default, the
du command shows the disk space used by the directory or file. To find the apparent size of a directory, use the
--apparent-size option. The “apparent size” of a file is how much data is actually in the file.
When you transfer a directory via SCP, Rsync., or SFTP the amount of data that is transferred over the network is the apparent size of the files. This is why the size of space on the disk used on the source when displayed with
--apparent-size) is not the same as the size on the target.
du command can also be combined with other commands with pipes.
For example, to print the 5 largest directories within the
/var directory, you would pipe the output of
du to the
sort command to sort the directories by their size and then pipe the output to the
head command that will print only the top 5 directories: