Table of Contents
When listing the contents of a directory using the ls command, you may have noticed that the size of the directories is almost always 4096 bytes (4 KB). That’s the size of space on the disk that is used to store the meta-information for the directory, not what it contains.
[root@kms]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 3.9G 0 3.9G 0% /dev
tmpfs 3.9G 0 3.9G 0% /dev/shm
tmpfs 3.9G 369M 3.6G 10% /run
tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
/dev/sda2 30G 4.2G 26G 15% /
/dev/sda1 497M 134M 364M 27% /boot
tmpfs 799M 0 799M 0% /run/user/0
/dev/sdb1 16G 45M 15G 1% /mnt/resource
The command you’ll want to use to get the actual size of a directory is du, which is short for disk usage.
Getting the Size of a Directory
The 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.
sudo du -sh /var
The output will look something like this:
[root@kms]# sudo du -sh /var
1.7G /var
Get the disk usage of the first-level subdirectories
What if you want to display the disk usage of the first-level subdirectories? You have two options:
1. The first one is to use the asterisk symbol (*) as shown below, which means match everything that doesn’t start with a period (.). The -c option tells du to print a grand total of all sizes:
sudo du -shc /var/*
[root@kms]# sudo du -shc /var/*
0 /var/account
462M /var/cache
0 /var/crash
8.0K /var/db
0 /var/empty
902M /var/lib
0 /var/local
274M /var/log
0 /var/mail
36M /var/ne
0 /var/nis
17M /var/spool
0 /var/tmp
816K /var/www
0 /var/yp
1.7G total
2. Another way to get a report about the disk usage of the first-level subdirectories is to use the –max-depth option:
sudo du -h --max-depth=1 /var
[root@kms usr]# sudo du -h --max-depth=1 /var
0 /var/account
462M /var/cache
0 /var/crash
8.0K /var/db
0 /var/empty
902M /var/lib
0 /var/local
274M /var/log
0 /var/mail
36M /var/ne
0 /var/nis
17M /var/spool
0 /var/tmp
816K /var/www
0 /var/yp
1.7G total
Find the 5 largest directories
The 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:
sudo du -h /var/ | sort -rh | head -5
[root@kms]# sudo du -h /var/ | sort -rh | head -5
1.7G /var/
902M /var/lib
565M /var/lib/waagent
462M /var/cache
460M /var/cache/yum/x86_64/7
Conclusion
In Linux, you can get the size of a directory using the du command.