Du Command - Estimate File Space Usage | Online Free DevTools by Hexmos

Estimate file space usage with the Du command. Learn how to find top space-consuming files and directory sizes. Free online tool for developers.

Du Command

Estimate File Space Usage with Du

The du command is a powerful utility in Unix-like operating systems used to estimate file space usage. It recursively displays the disk space used by each file and directory within a specified path. This guide provides practical examples of how to leverage du for effective disk management.

Find Top Space-Consuming Files

To identify the top 20 largest files or directories on a filesystem, you can combine du with sort and head. This is particularly useful for freeing up disk space. The example below uses sudo to ensure full access to all directories.

# du
# Estimate file space usage

# With 'root' privileges, use du(1), sort(1), and head(1) to display a list of
# the top 20 space-consuming files in whichever storage medium '/' is mounted.
#
# Here, du(1) is using the `-x` flag to keep to the one filesystem, which is
# important for getting accurate results on the filesystem on which you
# might, for example, be needing to free space.
#
# In order to sort the human-readable file sizes, sort(1) is using the `-h`
# flag, the `-k` flag to specify the column to sort (first), and its using
# the `-r` flag to reverse the sorting, so we see the highest size first.
#
# To then show the top-20 lines, we use head(1) and specify the number of lines
# via the `-n` flag. The default number of lines displayed by head(1) and
# tail(1) is 10.
#
# Root privileges are gained for this task by using sudo(8) on bash(1) in order
# to have a new root-owned BASH session, which then executes the commands
# proceeding the `-c` flag.
sudo bash -c 'du -xh / | sort -rhk 1 | head -n 20'

Display Total Directory Size

You can easily get a summary of the disk usage for the current directory or specific directories. The -s flag summarizes the total size, and -h provides human-readable output (e.g., KB, MB, GB).

# Display just the total human-readable size of the current working directory.
du -sh

# Display the total human-readable size of the three provided directories, as
# well as the grand total of the combined directories.
du -chs ~/Desktop ~/Pictures ~/Videos
# You could potentially make this task a bit easier with BASH brace expansion.
du -chs ~/{Desktop,Pictures,Videos}

Understanding Du Command Options

The du command offers various options to customize its output. Key options include:

  • -h, --human-readable: Print sizes in human-readable format (e.g., 1K, 234M, 2G).
  • -s, --summarize: Display only a total for each argument.
  • -c, --total: Produce a grand total.
  • -x, --one-file-system: Skip directories on different filesystems.

By mastering these options, developers can efficiently monitor and manage disk space across their systems.

Further Resources