Back to writing
archived

Linux Commands: du

Use the Linux du command to inspect file and directory disk usage, choose human-readable output, and control traversal depth.

du is used to display disk usage statistics. It’s a simple tool to calculate and print the disk space used by files or directories. Let’s see how to use it.

You can simply type du or du <directory-name> in your terminal and it will print the size.

Terminal output showing directory size with du

In the above example, it gives you the size of the directory. The unit is implementation-dependent: GNU du reports 1 KiB blocks by default, while other systems may use a different block size. Use du -h when you want a human-readable result rather than assuming the number is bytes.

To print each and every file and their respective size we will need to use the du -a command. If you just want to print the sizes in the root of the directory and don’t want to go deep inside each directory you can use du *.

du listing individual files and their sizes

You can apply various options to manipulate the output.

  • -a: Display an entry for each file in a file hierarchy.
  • -c: Display a total size.
  • -d: Specifies how many levels deep this command should print the files.
  • -h: Human-readable output.
  • -g: Display the size in Gigabytes.
  • -k: Display the size in Kilobytes.
  • -m: Display the size in Megabytes.

Human-readable disk usage output from du

Practical Usage

Suppose you want to print the top files that are consuming the most disk space. You can pipe the output of the du to sort and then print the head. Largest files found by piping du through sort and head

Conclusion

I have been extensively using this command to resolve production issues. Whenever we have an issue related to space on VM boxes I use this command to figure out what is exhausting the space. So it comes in handy in solving the real-world problem faced while debugging production issues which is related to disk space.