Description

We can use the Disk Usage command du to find the size of a directory from the command line on a Ubuntu machine.

  • The word du stands for Disk Usage.
  • This utility summarizes the disk usage of all the files of a directory to achieve the size of a directory.

This command can be run on a file or a directory.

Syntax

Here is the basic syntax of the disk usage utility.

  • The option -h represents human-readable, which prints the sizes in human-readable formats, like 1K, 10M, 5G, etc.,
  • The option -s represents summarize, which displays the total size of the specified directory.
  • The option -a displays the size of each file and subdirectory of the specified directory.
  • Command without the -s option displays the size of the specified directory and its subdirectories as well.
du -hs directory_path

Examples

The below command returns the size of the "assets" directory in the working directory.

du -hs assets

The below command returns the size of the same "assets" directory using its absolute path.

du -hs /var/www/assets

The below command returns the size of the "assets" directory, along with the size of each of its files and subdirectories.

du -ha /var/www/assets

The below command returns the size of the "assets" directory, along with the size of each of its files and subdirectories, sorted by size in descending order.

  • The sort sorts the list of files and subdirectories within the specified directory.
  • The option -r represents reverse, which sorts the list in descending order.
  • The option -h represents human-readable, which prints the sizes in human-readable formats, like 1K, 10M, 5G, etc.,
du -h /var/www/assets | sort -rh

The below command returns the size details of the current working directory, as we did not specify any directory.

du -ha

Access Issues

In case, if the user doesn't have permissions on a file or directory on which this command is run, then the below error or a similar error is issued. In such a situation, the user needs to run this command as a sudo user to successfully execute it.

du: cannot read directory

Related Links