# du

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/du

## Quick definition

The du command shows how much storage space a file or folder is using on your computer. It helps you find large files and understand which directories are taking up the most disk space. You run it in the terminal, and it gives you the size in kilobytes, megabytes, or gigabytes.

## Simple meaning

Imagine you have a big closet where you store clothes, shoes, and boxes. Over time, you forget what is inside some of the boxes and how much space each item takes. The du command is like a helper that goes through every shelf, drawer, and box, measures exactly how much space each thing occupies, and gives you a list. It does not move anything or change how things are stored, it only reports sizes.

In computing terms, du stands for "disk usage." When you run the du command on a folder, it looks at every file inside that folder, including files in subfolders, and adds up their sizes. It then displays the total for each folder, so you can see which folders are the "heavy" ones. This is very useful when your computer or server is running low on storage because du helps you find what is consuming the most space. For example, if you have a folder named "Downloads" on your laptop, du can tell you exactly how many gigabytes that folder uses, broken down by subfolders like "Documents" or "Videos."

The du command does not change any files, it only reads their metadata (size information) from the file system. It works on all Unix-like systems such as Linux and macOS. For IT professionals, du is one of the first tools used for storage troubleshooting because it is fast, reliable, and available on nearly every server without needing extra installation.

## Technical definition

The du command, short for "disk usage," is a standard utility in Unix and Unix-like operating systems (including Linux and macOS) that reports the file space usage of directories and files. It walks the directory tree, reads the size of each file from the file system's inode metadata, and accumulates the total for each directory. The command is part of the GNU Core Utilities in Linux and is specified by POSIX, ensuring consistent behavior across compliant systems.

When du is invoked without any options, it recursively traverses every subdirectory starting from the current working directory (or a given path) and prints the disk usage for each directory in 1024-byte blocks. The basic output shows a number (the size in blocks) followed by the directory name. For example, "du /home/user" will list every subdirectory under /home/user with its block count. Each file's size is obtained via the stat() system call, which retrieves the st_blocks field from the inode, this field represents the number of 512-byte blocks allocated to the file on disk, which may differ from the file's logical size due to filesystem block size and sparse files.

Common options modify du's behavior significantly. The -h (human-readable) flag converts block counts into KiB, MiB, or GiB with appropriate suffixes. The -s (summarize) flag shows only the total for each argument, omitting subdirectory details. The -a (all) flag includes individual file sizes instead of just directories. The --exclude and --max-depth options give granular control over what du reports. The -c (total) option adds a grand total at the end, useful when multiple directories are specified.

In practice, du interacts closely with the underlying file system. It respects symbolic links only when the -L option is used; otherwise, it reports the size of the link itself, not the target. Hard links are counted only once per inode, but this can lead to confusion in snapshots or copy-on-write file systems like ZFS or Btrfs, where du may report space usage that does not match the actual disk consumption. For network file systems (NFS, SMB), du traverses the remote directory and may incur network latency, so it is often combined with '--one-file-system' (-x) to avoid crossing mount points.

IT professionals frequently use du in scripts for automated disk monitoring. For example, a cron job might run "du -sh /var/log" daily to alert if log files exceed a threshold. Understanding the difference between "apparent size" (the logical size of a file) and "disk usage" (the actual blocks consumed) is critical: sparse files and compression can make these values diverge. The '--apparent-size' flag forces du to report the logical size instead.

## Real-life example

Think of your kitchen pantry. You have shelves, cabinets, and a few big bins holding rice, pasta, snacks, and canned goods. After a few months of buying groceries, you notice the pantry is getting cramped, but you are not sure which items are taking up the most space. The du command is like taking everything out, measuring the volume of each bin and box, and writing down the measurements. It tells you that the rice bin takes up 10 liters, the pasta box takes 5 liters, and the snack basket takes 3 liters, but it does not throw anything away or reorganize the shelves.

In the digital world, instead of liters, du measures kilobytes or gigabytes. If your computer tells you the hard drive is 90% full, you can open a terminal and run "du -sh /*" to see which top-level folders are the largest. You might find that a folder named "Videos" uses 200 GB, while "Documents" uses only 5 GB. Then you can run "du -sh /Videos/*" to find which specific video file or subfolder is the culprit. This is exactly like checking which container in the pantry is the biggest before deciding to donate or discard.

Another analogy: imagine you manage an office with many filing cabinets. Each drawer holds folders, and each folder holds papers. Du is the assistant who goes through every drawer, folder, and paper, counts the pages, and gives you a report, without shuffling or removing anything. This saves you from opening every drawer manually.

## Why it matters

In real-world IT operations, disk space management is a constant concern. Servers, workstations, and cloud instances all have finite storage, and running out of space can cause applications to crash, databases to stop writing, and entire services to fail. The du command is the primary tool for diagnosing these storage issues because it gives immediate, granular visibility into where space is being consumed. Without du, administrators would have to browse through file systems manually, guessing which directories hold large files.

For example, a web server might suddenly alert that /var/www is 95% full. A system administrator can run "du -sh /var/www/*" to see that a single log file is 50 GB, far larger than expected. With that information, they can compress, rotate, or delete the log file to free up space, all within minutes. This speed is critical in production environments where downtime costs money.

Du also matters for capacity planning. By regularly running du on key directories (like /home, /var, /tmp), system administrators can track growth trends over time. If /home grows by 10 GB every month, they can predict when the disk will fill up and plan an upgrade before an incident occurs. In data centers, du scripts integrated with monitoring tools (like Nagios or Prometheus) send alerts when folder sizes exceed thresholds, enabling proactive maintenance.

du is often used in auditing and compliance. If a security policy requires that certain directories (like /var/log) be kept under a specific size, du can verify compliance quickly. It is also used during forensic analysis to identify which files or directories are unusually large, which might indicate data hoarding or malware storing large payloads.

## Why it matters in exams

For general IT certification exams, such as CompTIA A+, CompTIA Linux+, and LPI Linux Essentials, du is a fundamental command that appears in the" disk management" and "command line interface" domains. In CompTIA A+ (220-1102), candidates must know how to use command-line tools for storage management, including du, to identify disk usage and free space. Questions may ask which command can show the size of a directory and its subdirectories, with multiple-choice options including df, ls, fdisk, and du.

In the CompTIA Linux+ (XK0-005) exam, du is explicitly listed under objectives for "Managing Storage" and "Working with the Linux Command Line." Exam questions often present a scenario where a system administrator needs to find which directory is consuming the most disk space, and the correct answer involves using du with appropriate flags like -h and -s. The exam may also test understanding of the difference between du and df: df reports free and used space on entire file systems, while du reports usage of specific directories. A common trap question asks which command to use to see the size of the /var/log directory in human-readable format, the correct answer is "du -sh /var/log."

For the Linux Professional Institute (LPI) exams, such as LPIC-1, du is part of Objective 104.1 (Manage disk partitions and file systems). Candidates must know how to use du to analyze disk usage, including options like --max-depth and --exclude. The exam may include questions that require interpreting du output to identify which directory is largest, or combining du with sort and head to find the top ten largest directories. For example: "A user reports that /home is full. Which command would you use to find the three largest directories under /home?" The answer: du -sh /home/* | sort -rh | head -3.

Even in cloud or DevOps-related certifications like AWS Certified SysOps Administrator or Red Hat Certified System Administrator (RHCSA), du is expected as basic Linux knowledge. While these exams may not test du syntax directly, they assume candidates can use it to troubleshoot EC2 instance storage. In AWS, if an EC2 instance's EBS volume is filling up, du is the primary CLI tool to find space hogs before resizing or cleaning.

## How it appears in exam questions

Exam questions about du typically fall into three categories: command syntax, scenario-based troubleshooting, and comparison with other tools. In command syntax questions, the learner is asked to identify the correct flag to achieve a specific goal. For example: "Which du flag displays sizes in a human-readable format?" with options like -h, -k, -m, or -s. The answer is -h. Another variation: "Which command shows the total disk usage of the /etc directory without listing subdirectories?" The correct answer is du -sh /etc.

Scenario-based questions present a real-world problem. For instance: "A server administrator notices the disk on /dev/sda1 is 90% full. They need to identify which directory under /var is consuming the most space. Which command should they run first?" The answer: du -sh /var/* | sort -rh. The question may then ask what the output shows, requiring the learner to interpret sample du output that lists directories and their sizes. Another scenario: "After running du -sh /home, the output shows 500M. The user claims they only stored 100M of data. What could explain the discrepancy?" This tests understanding of hidden files, journal logs, or filesystem overhead.

Comparison questions pit du against df, ls, or fdisk. For example: "A technician needs to see how much space each top-level directory uses on the system. Which two commands can help?" Options might include df -h (shows filesystems, not directories) and du -sh /* (correct). Another: "What is the difference between du and df?" The answer: df reports free and used space on mounted filesystems, while du reports the size of a specific directory tree. A trap could ask: "Which command shows the available disk space on a partition?", learners might mistakenly pick du, but the correct answer is df.

Performance-based questions (PBQs) in CompTIA Linux+ may simulate a terminal where the candidate must run du commands to locate large files and then delete or compress them. For example, the simulation provides a server with a critically full /var/log directory, and the learner must use du to identify which log file is largest, then use a command like gzip to compress it. PBQs often require combining du with find or grep for advanced filtering.

Finally, some questions test obscure flags: "Which du option prevents it from crossing filesystem boundaries?" Answer: -x (--one-file-system). Or: "Which option shows the apparent size instead of disk usage?" Answer: --apparent-size. These appear in more advanced exams like LPIC-2.

## Example scenario

You are a junior IT support technician for a small company. The finance department's shared computer has a 250 GB hard drive, and employees are getting warnings that storage is almost full. The manager asks you to find out what is using all the space without deleting anything important. You access the computer via remote connection and open the command terminal. You decide to run du to diagnose the problem.

First, you switch to the root directory by typing "cd /" then run "du -sh /*" to list the total size of each top-level folder. The output shows that /Users takes 200 GB, while all other folders together use only 30 GB. Now you know the problem is inside the Users folder. Next, you narrow it down: "du -sh /Users/*" shows a list of user home folders. You see that the user "jdoe" has 180 GB in their home directory, which is highly unusual.

You drill deeper: "du -sh /Users/jdoe/*" reveals that the Downloads folder is 150 GB. That is suspicious. You check further with "du -sh /Users/jdoe/Downloads/* | sort -rh" and see a file named "backup_video_2023.mp4" that is 149.9 GB. You call jdoe and ask if they still need that file. They confirm it was an old personal video they forgot about and give permission to delete it. You delete the file, run du again, and see that free space is restored to 150 GB. You report back to the manager, who is relieved.

This scenario shows how du helps systematically locate storage hogs by starting broad, then narrowing down. Without du, you might have wasted hours clicking through folders in the graphical interface.

## Common mistakes

- **Mistake:** Assuming du shows available free space instead of used space.
  - Why it is wrong: du calculates the disk space used by files/directories, not the remaining free space. Confusing du with df leads to incorrect troubleshooting.
  - Fix: Use df -h to see free and used space on filesystems. Use du to see how much space specific directories consume.
- **Mistake:** Omitting the -s (summarize) flag and getting a huge wall of output for large directories.
  - Why it is wrong: Without -s, du lists every subdirectory individually, which can produce thousands of lines and make it impossible to find the big folders quickly.
  - Fix: Always use -s with a target directory, or combine with --max-depth=1 to limit output to one level.
- **Mistake:** Forgetting the -h flag and reading sizes in block count instead of human-readable format.
  - Why it is wrong: Default block sizes (512 or 1024 bytes per block) are not intuitive. A result of 2048000 blocks does not immediately tell you it is about 2 GB.
  - Fix: Add -h to all du commands for sizes in KB, MB, GB. For example: du -sh /home.
- **Mistake:** Running du on a network mount without the --one-file-system flag and crossing into other filesystems.
  - Why it is wrong: If a directory contains a mount point (like /mnt/nfs), du will traverse into that network share and potentially hang or show incorrect totals.
  - Fix: Use du -x (--one-file-system) to stay on the current filesystem, or exclude mount points with --exclude.
- **Mistake:** Believing du output counts file sizes exactly, ignoring sparse files and metadata overhead.
  - Why it is wrong: Sparse files (with empty holes) have a large logical size but small disk usage. Du reports logical size with --apparent-size and actual blocks without it. Metadata (inodes) is not included in du output.
  - Fix: Understand the difference: for actual disk consumption, rely on the default du output (block count). For file content size, use --apparent-size.

## Exam trap

{"trap":"In a multiple-choice question, the answer choices include both 'du -sh /dir' and 'df -h /dir', and the scenario asks which command shows the size of a specific directory. Many learners pick df because they remember 'df shows disk usage,' but df shows filesystem-level free/used space, not per-directory size.","why_learners_choose_it":"Learners often memorize that df is for disk usage and du is for directory usage, but in the heat of the exam they confuse the two. The word 'disk' in 'df' sounds similar to 'directory size' to a stressed test taker.","how_to_avoid_it":"Remember the mnemonic: df = Disk Free (free space on a partition), du = Directory Usage (size of directory tree). On exam day, read the question carefully: if it asks 'how much space is used by /var/log?' it is always du. If it asks 'how much free space on /dev/sda1?' it is df."}

## Commonly confused with

- **du vs df:** df reports disk free space, how much space is available and used on entire mounted file systems (partitions). du reports the size of a specific directory and all its contents. df gives a high-level overview of partitions; du gives a drill-down into folders. (Example: To see how full your C: drive (or /) is, use df -h. To see how large the /var/log folder is, use du -sh /var/log.)
- **du vs ls -l:** ls -l lists individual file sizes within a directory but does not sum up subdirectory sizes. du recursively totals all files in subdirectories. ls shows a snapshot of one level; du shows cumulative usage. (Example: Running ls -l /home/user shows each file's size, but the total folder size is not computed. Running du -sh /home/user gives the total for everything inside.)
- **du vs ncdu:** ncdu (NCurses Disk Usage) is an interactive TUI tool that provides a visual, sortable interface for disk usage, built on the same data du gathers. Du is a simple command-line tool; ncdu adds an interactive browser with arrow key navigation, but both report similar disk usage numbers. (Example: If you want a quick command in a script, use du. If you want to interactively explore which directories are large, use ncdu.)

## Step-by-step breakdown

1. **Invoke the du command** — Open a terminal and type du followed by optional flags and the target path. Example: du -sh /home/user. The shell executes du, which begins reading the directory tree.
2. **Directory traversal** — du recursively walks through the target directory and every subdirectory. For each directory, it reads the list of entries using the readdir() system call. On large file systems this can take time, which is why use -s to skip deeper listing.
3. **File size retrieval via inode metadata** — For each file found, du calls stat() to get the file's inode information. The key field is st_blocks, which gives the number of 512-byte blocks allocated to the file on disk. This accounts for filesystem block sizes, sparse files, and indirect blocks.
4. **Accumulation and optional formatting** — du adds the st_blocks value for all files within a directory to compute that directory's total. If the -h flag was used, du converts block counts into KiB, MiB, or GiB by dividing by 1024 repeatedly. Without -h, output is in 1024-byte blocks.
5. **Output display** — du prints each directory (or file with -a) and its accumulated size sequentially to standard output. With -s, only the total for the top-level argument is printed. The output can be piped to sort, grep, or head for further processing. The command exits with code 0 on success, or 1+ if errors occurred (e.g., permission denied for a subdirectory).

## Practical mini-lesson

The du command is indispensable for any IT professional managing Linux or macOS systems. To use it effectively, you need to understand the relationship between du, the file system, and the underlying block allocation. Every file on disk is stored in blocks, typically 4 KiB blocks on modern Linux systems. When du reports '100M' for a directory, it means the files in that directory consume 100 MiB of disk space, not necessarily 100 MiB of file content (due to fragmentation, indirect blocks, and metadata).

In practice, the most common du workflow is to identify large directories for cleanup. A sysadmin might write a daily cron job: "du -sh /var/log /home /tmp /backup | mail -s 'Disk Usage Report' admin@company.com". When an alert triggers, the admin runs an interactive series: du -sh /* then du -sh /var/* then du -sh /var/log/*. For automation, du works well in scripts because its output is predictable and can be parsed.

One advanced technique is to use du with the 'sort' command to list the largest directories. Example: "du -h /var | sort -rh | head -10". The -r flag sorts descending, and -h tells sort to understand human-readable sizes (requires GNU sort). On macOS (BSD sort), this flag is not available, so alternatives like "du -sk /var/* | sort -rn | head -10" are used instead, where -sk gives sizes in KiB sorted numerically.

Another nuance is dealing with permission errors. When du encounters a directory it cannot read (e.g., /root in a user session), it prints an error to stderr and skips that subtree. This means the reported total may be less than the actual usage. To avoid this, run du as root (with sudo) when checking system directories like /etc or /var.

What can go wrong? If du is run on a very large directory (like a multi-terabyte NFS mount), it can take hours and consume significant CPU and disk I/O. In production, avoid running du on the root filesystem during peak hours. Use the --exclude flag to skip backup directories or mount points. Also, on snapshot-based filesystems like ZFS or Btrfs, du can report seemingly inflated usage because of snapshot clones. In those cases, use zfs list or btrfs filesystem du instead for accurate pool-level space accounting.

## Memory tip

du = Directory Usage. Think: 'du' is 'you' checking how much space YOUR folder takes.

## FAQ

**What does du stand for?**

du stands for 'disk usage.' It is a command-line utility that estimates the space used by files and directories on Unix-like operating systems.

**How do I see disk usage in human-readable format?**

Use the -h flag with du. For example: du -sh /home. This shows sizes in kilobytes (K), megabytes (M), or gigabytes (G) instead of raw block counts.

**What is the difference between du and df?**

df reports free and used space on entire file systems (partitions). du reports the total size of a specific directory and its contents. Use df for partition-level overview, du for folder-level detail.

**Why does du sometimes show a different size than the file's properties?**

Du reports the actual disk blocks allocated (which can be larger due to fragmentation or metadata overhead) or smaller if the file is sparse. The file's properties may show logical size. Use du --apparent-size to match logical size.

**Can du be used on a remote server?**

Yes, if you have SSH access. You can run du via SSH: ssh user@server 'du -sh /var/log'. The command runs on the remote server and returns results to your local terminal.

**Why is du taking a long time on /home?**

Large directories with many files or deep nesting cause du to traverse extensively. Use -s (summarize) or --max-depth=1 to limit the work. Also consider using 'du -x' to stay on one file system and avoid network mounts.

## Summary

The du command is a simple yet powerful tool for measuring disk usage in Unix-like systems. It recursively scans directories, sums up file sizes using inode block counts, and outputs the total for each directory. For IT professionals, du is essential for troubleshooting disk space shortages, capacity planning, and routine storage audits. Understanding its flags, especially -h, -s, -x, and --max-depth, transforms it from a basic utility into a precision instrument for storage management.

In certification exams, du appears in basic Linux+, A+, and LPI tests as a command-line skill. Candidates must know when to use du versus df, how to interpret its output, and how to combine it with sort and head for advanced analysis. The most common exam pitfalls involve confusing du with df, forgetting human-readable flags, and misreading sparse file output.

Mastering du gives new IT professionals a quick and reliable way to answer the question, 'What is taking up all my space?' That skill alone can prevent server outages, reduce storage costs, and build confidence in system administration. Study the flags, practice on your own machine, and remember: du is your first responder for disk emergencies.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/du
