/

Linux Commands: du - A Quick Guide to Calculating File and Directory Space Usage

Linux Commands: du - A Quick Guide to Calculating File and Directory Space Usage

The du command is a powerful tool in Linux that allows you to determine the space usage of files and directories. By using this command, you can easily find out how much disk space is being consumed by your data.

To calculate the size of a directory as a whole, simply run the command du. It will display the total size of the directory in bytes. For example:

1
du

Screenshot

In the above example, the du command shows that the directory size is 32 bytes.

If you want to calculate the size of each file individually, you can use the du * command. This will display the size of each file in the directory. For example:

1
du *

Screenshot

To make the output more readable, you can use the -h option. This will show the sizes in a human-readable format, adapting to the size. For example:

1
du -h

Screenshot

Additionally, you can use the -m option to display sizes in Megabytes or the -g option to display sizes in Gigabytes.

By adding the -a option, you can print the size of each file in the directories as well. This can be useful when you want to get a comprehensive view of the space consumed. For example:

1
du -a

Screenshot

If you want to sort the directories by size, you can use the following command:

1
du -h <directory> | sort -nr

This command will display the size of each directory in a human-readable format and sort them in reverse order. To limit the results to the top 10 directories, you can pipe the output to head. For example:

1
du -h <directory> | sort -nr | head -n 10

Screenshot

It’s important to note that the du command is not limited to Linux. It works on other Unix-based systems such as macOS, WSL (Windows Subsystem for Linux), and any environment that has a UNIX-like shell.

Useful Tags: Linux, du command, file size, directory size, disk space, command-line tool