Show Size of Directory Linux

Linux only shows the size of the metadata for directories when using the ls command, not the size of its contents. The command we need to use to get the real directory size is du, which is short for disk usage.

 

In this tutorial, we will learn how to use the du command in Linux to get human-readable size info about any directory.

 

du Syntax

The du command takes a list of optional arguments followed by an optional directory path.

 

du [OPTIONS] [FILE]

 

Get the Size of a Directory

Let's say we want to find the size of a directory called app in the current working directory in a human-friendly format. We could use this du command:

 

du -sh app/
208K app/

 

 

As you can see in the example above, we get the directory size in KB, MB, GB, .etc. Here is what the flags do in the above command:

 

  • -s - this tells du to get the total size of all the subdirectories and combine them into a total size (summary).
  • -h - this converts the output into an understandable size format.

 

 

You may need to run the command in sudo mode if a permissions error appears:

 

sudo du -sh app/

 

Get Size of Subdirectories

To get the total size of a directory and its first-level subdirectories we can use the --max-depth flag.

 

du -h --max-depth=1 public/
136K public/css
6.3G public/images
1.7M public/js
4.0K public/.well-known
16K public/public
2.7M public/fonts
13G public/

 

To get the size of subdirectories deeper down the hierarchy, increase the value of --max-depth, though as you can image the output will probably be very verbose beyond level 1.

 

Get The Largest Subdirectories in a Directory

With du, like all Linux terminal programs, we can pipe the output of the first command into another program and so on and so forth. As a result, we can sort the output of du from largest to smallest and take the top ten result using head.

 

du -h public/ | sort -rh | head -10
13G	public/
6.3G	public/images
632M	public/images/movies
205M	public/images/xbox-one
137M	public/images/books
126M	public/images/dragon-ball
116M	public/images/volcano
112M	public/images/yugioh
104M	public/images/premiere-league-player
101M	public/images/song

 

Conclusion

You can now find the size of directories in Linux in a variety of different ways.