du - macOS


Overview

The du (disk usage) command in macOS is used to estimate and report the file space usage of a given set of files or directories. This tool can help users manage disk space by providing detailed insights into which files and directories are consuming the most space. It is particularly useful in system administration for monitoring and maintaining file system usage.

Syntax

The basic syntax of the du command is:

du [options] [file...]
  • [options]: Flags that modify the function of du.
  • [file…]: One or more files or directories to analyze. If no file is specified, du uses the current directory by default.

Options/Flags

du supports a variety of options and flags that tailor its output:

  • -a, –all: Include both files and directories in the output.
  • -c, –total: Display a grand total for all arguments at the end of the output.
  • -h, –human-readable: Print sizes in human-readable format (e.g., 1K, 234M, 2G).
  • -r: Show disk usage even for unreadable files.
  • -s, –summarize: Display only the total for each argument.
  • -x, –one-file-system: Stay on the same filesystem, ignoring directories on different filesystems.
  • –max-depth=N: Limits the display depth to N levels of subdirectories.

Examples

  1. Basic Usage:
    Calculate the disk usage of the current directory:

    du
    
  2. Human Readable Form:
    Show disk usage of the documents directory in a human-friendly format:

    du -h ~/Documents
    
  3. Summarize:
    Get the total disk usage of a specific directory:

    du -sh ~/Downloads
    
  4. Combining Flags:
    List the disk usage of all files and directories in /var up to two directory levels deep, with human-readable sizes:

    du -ah --max-depth=2 /var
    
  5. Calculate Total Size:
    Calculate the combined size of multiple directories:

    du -c -h ~/Documents ~/Downloads
    

Common Issues

  • Permission Denied: Users may see “Permission denied” errors if du tries to access directories without appropriate permissions.

    • Solution: Run du with sudo to gain elevated permissions.
  • Large Output: Without flags, du can produce overwhelming output for directories with many files.

    • Solution: Use the -h and -s flags for more manageable summaries.

Integration

Combining du with other commands can provide powerful insights and automations:

# Find the five largest directories
du -sh * | sort -rh | head -5

This uses sort to order directories by size and head to limit the output to the largest five.

  • df: Reports the disk space usage of entire filesystems.
  • sort: Useful for ordering du output.
  • head, tail: Display the beginning or end of lists, often combined with du.

For detailed official documentation, visit Apple’s manual pages via the man du command or check Apple’s developer documentation online.