Website Vidya
Linux & ServersStep-by-Step Guide

Check Linux Folder Size: du, ncdu & Disk Space Guide

Learn linux folder size with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
Check Linux Folder Size: du, ncdu & Disk Space Guide
AI Executive SummaryWebsiteVidya AI

10 min read

Learn linux folder size with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What du Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Monitoring and auditing linux folder size is a critical task for systems engineers, database administrators, and DevOps teams. Whether responding to high disk usage alerts on root partitions, investigating runaway Docker volumes, or tracking log file growth, knowing how much physical storage a directory consumes prevents filesystem exhaustion.

The primary tool for calculating directory sizes is du (disk usage), part of GNU coreutils. Unlike simple file listing tools that report apparent file lengths, du walks directory trees and queries filesystem metadata to compute the actual disk block allocation consumed by files, subdirectories, and hard links.

While du -sh provides instant summaries of individual directories, combining du with sort, find, and modern interactive visualizers like ncdu turns raw byte numbers into actionable diagnostics during emergency disk reclamation.

Advertisement
Check Linux Folder Size: du, ncdu & Disk Space Guide — syntax, flags, and practical terminal workflow diagram
Check Linux Folder Size: du, ncdu & Disk Space Guide — command syntax, key options, and production workflow reference.

What du Does and When to Use It

To measure folder sizes accurately, du invokes the stat(2) or fstatat(2) system call on every discovered inode during its depth-first traversal. The kernel returns a stat structure containing two size-related fields: st_size (the apparent file size in bytes) and st_blocks (the number of 512-byte blocks physically allocated on storage). By default, du calculates storage using st_blocks, correctly accounting for filesystem block allocation granularity (typically 4096-byte blocks on ext4 and XFS) and sparse files with unallocated zero-byte holes.

A crucial architectural responsibility of du is hard link deduplication. Every inode maintains a reference counter (st_nlink). If multiple directory entries point to the same physical inode, du tracks seen device/inode number pairs (st_dev and st_ino) in an internal hash table, counting the physical storage blocks only once. If you pass -l (--count-links), du counts duplicate hard links repeatedly, which distorts true physical consumption.

Under the hood, du gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -s, -h, -d <N>, -a turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The du utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether du is installed and inspect which binary path and version your shell resolves:

type -a du
du --version 2>/dev/null || man -f du

# Illustrative output (reviewed against documentation)
du is /usr/bin/du
du (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

du [OPTION]... [FILE]... | du -sh [DIRECTORY]...

The standard syntax for disk usage inspection is du [OPTION]... [FILE].... If no file or directory argument is specified, du reports disk usage for the current working directory. The two most common flags are -s (--summarize), which displays only a single total sum for each argument rather than listing every nested folder, and -h (--human-readable), which formats byte values into convenient suffixes (K, M, G, T).

To control the depth of recursive traversal without flooding the terminal, GNU du provides -d or --max-depth= (e.g. --max-depth=1 to inspect immediate subdirectories only). Other vital options include -x (--one-file-system) to skip directories located on separate mount points (preventing traversal into NFS or pseudo-filesystems like /proc), and -a (--all) to count individual files alongside directories.

  • 0 — Disk usage calculation completed successfully across all specified paths.
  • 1 — Minor operational failure, such as encountering unreadable directories due to permission restrictions.
  • 2 — Malformed command-line options or invalid syntax arguments provided.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-s--summarizeDisplays only a total disk usage summary for each argument.
-h--human-readablePrints sizes in human-readable format with power-of-1024 suffixes (e.g., 1K, 234M, 2G).
-d <N>--max-depth=<N>Prints total for directory only if it is N or fewer levels below the command argument.
-a--allWrites counts for all files, not just directory containers.
-c--totalProduces a grand total line at the bottom of the output.
-x--one-file-systemSkips directories on different filesystems/mountpoints.
--apparent-size--apparent-sizePrints apparent byte sizes rather than physical disk block usage.
--exclude=<PATTERN>--exclude=<PATTERN>Excludes files and directories matching the specified shell glob pattern.

The combination du -sh * | sort -h is one of the most frequently used diagnostic pipelines in Linux server administration. Passing * expands all unhidden items in the current directory, -s summarizes each item, and sort -h performs a human-numeric sort that correctly orders kilobytes (K), megabytes (M), and gigabytes (G) from smallest to largest.

Advertisement

Always pass -x (--one-file-system) when analyzing root partition utilization (e.g., du -xh --max-depth=1 /). Without -x, du will traverse into virtual filesystems like /proc and /sys, external network shares, and separate backup volumes, hanging the process and returning misleading disk space numbers.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Check the Total Size of a Single Directory

Display the total disk consumption of a target directory in human-readable units.

du -sh /var/log

# Illustrative output (reviewed against documentation)
248M	/var/log

The -s flag summarizes the directory into a single aggregate total, and -h formats the output as 248 Megabytes.

2. List and Sort Immediate Subdirectory Sizes

Inspect the size of immediate subdirectories within a folder and sort them from smallest to largest.

du -h --max-depth=1 /var | sort -h

# Illustrative output (reviewed against documentation)
4.0K	/var/mail
12K	/var/spool
28M	/var/backups
248M	/var/log
1.4G	/var/lib
1.7G	/var

--max-depth=1 limits output to immediate subdirectories, and sort -h arranges lines by human-readable numeric values.

3. Find the Top 5 Largest Folders on the System

Scan the root filesystem while staying on one mount point to identify the top 5 space-consuming directories.

sudo du -xh --max-depth=1 / 2>/dev/null | sort -hr | head -n 5

# Illustrative output (reviewed against documentation)
18G	/
9.2G	/var
5.1G	/usr
2.4G	/opt
1.1G	/home

The -x flag prevents crossing into /proc or /mnt, sort -hr orders largest to smallest, and head -n 5 displays the top 5.

4. Compare Physical Disk Usage vs Apparent Size for Sparse Files

Observe how du reveals true disk block allocation versus apparent logical byte length on sparse files.

truncate -s 10G sparse.img
du -h sparse.img
du -h --apparent-size sparse.img

# Illustrative output (reviewed against documentation)
0	sparse.img
10G	sparse.img

Standard du reports 0 blocks physically allocated on disk, while --apparent-size reports the 10G logical unallocated size.

5. Calculate Total Size with an Aggregate Grand Total (-c)

Check multiple directory sizes simultaneously and display a combined grand total line at the end.

du -shc /etc /var/log /tmp

# Illustrative output (reviewed against documentation)
14M	/etc
248M	/var/log
8.0K	/tmp
263M	total

The -c flag sums each item's disk usage into an authoritative 'total' summary line.

6. Exclude Specific Directories Using Glob Patterns

Calculate project size while ignoring large build artifacts, node_modules, and git directories.

du -sh --exclude=".git" --exclude="node_modules" /home/admin/project

# Illustrative output (reviewed against documentation)
42M	/home/admin/project

The --exclude options filter out matched directory subtrees, measuring only core application source files.

Real-World Workflows, Pipelines, and Shell Automation

Emergency Disk Exhaustion Triage and Culprit Identification

When a root partition (/ or /var) hits 100% capacity, run this diagnostic script to isolate the largest space-consuming directories and unlinked open log files rapidly.

echo "=== Step 1: Filesystem Overview ==="
df -h /

echo "=== Step 2: Top 5 Consuming Directories ==="
sudo du -xh --max-depth=1 /var 2>/dev/null | sort -hr | head -n 5

echo "=== Step 3: Checking for Deleted Open Files Holding Disk Space ==="
sudo lsof +L1 2>/dev/null | head -n 5

# Illustrative output (reviewed against documentation)
=== Step 1: Filesystem Overview ===
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        40G   39G  850M  98% /

=== Step 2: Top 5 Consuming Directories ===
9.2G	/var
5.4G	/var/log
3.1G	/var/lib
220M	/var/cache
12K	/var/spool

=== Step 3: Checking for Deleted Open Files Holding Disk Space ===
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NLINK NAME
nginx    1420 root    4w   REG    8,1 2147483648     0 /var/log/nginx/access.log (deleted)

This triage combines df to verify capacity, du to identify space hogs in /var/log, and lsof to detect deleted files still held open by processes.

Automated Monthly Directory Storage Usage Reporting

Generate an automated disk usage breakdown of user home directories, exporting results to a CSV log for storage capacity planning.

REPORT_FILE="/var/log/home_storage_report.csv"
echo "Directory,SizeBytes,HumanSize,ReportDate" > "$REPORT_FILE"
DATE_STAMP=$(date +"%Y-%m-%d")

sudo du -b --max-depth=1 /home 2>/dev/null | while read -r bytes path; do
  human=$(numfmt --to=iec "$bytes" 2>/dev/null || echo "${bytes}B")
  echo "$path,$bytes,$human,$DATE_STAMP" >> "$REPORT_FILE"
done

echo "Report generated at $REPORT_FILE:"
head -n 5 "$REPORT_FILE"

# Illustrative output (reviewed against documentation)
Report generated at /var/log/home_storage_report.csv:
Directory,SizeBytes,HumanSize,ReportDate
/home/admin,4294967296,4.0G,2026-10-22
/home/developer,10737418240,10G,2026-10-22
/home,15032385536,14G,2026-10-22

The script records exact byte sizes alongside human-readable formatted strings, creating structured telemetry for storage capacity auditing.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding du inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Calculating folder size requires read and execute permissions on directories. If an unprivileged user runs du /root or du /var/lib/docker, du will print 'Permission denied' warnings for unreadable directories and omit their contents from the calculated total, resulting in an inaccurate undercount.

In security-sensitive environments, file sizes and directory presence can leak information about application activity or data volume. Run audit scripts with root or administrative privileges to obtain complete numbers while ensuring report files are protected with mode 0600.

GNU/Linux, BSD, and BusyBox Implementation Differences

The basic du command is standardized under POSIX.1-2017. However, the --max-depth option is a GNU extension. On BSD systems (macOS, FreeBSD), the equivalent flag is -d <depth> (e.g., du -h -d 1).

BusyBox du on minimal Alpine containers supports -s, -h, and -d, but may omit long options like --apparent-size or --exclude. For portable scripts, use short options: du -sh -d 1 /path.

Troubleshooting Common Errors and Diagnostics

du and df report completely different disk space numbers

Root Cause: A large log or data file was unlinked (deleted) with rm, but an active process still holds the file descriptor open. The kernel cannot free disk blocks until the process closes the file.

Resolution: Find processes holding deleted files open with lsof +L1 and restart the offending daemon.

sudo lsof +L1
sudo systemctl restart nginx

du: cannot read directory 'dir': Permission denied

Root Cause: The executing user lacks read or execute permissions on a subdirectory within the traversed path.

Resolution: Prepend sudo to execute du with superuser privileges, or suppress non-critical warnings using 2>/dev/null.

sudo du -sh /path/to/dir
# Or suppress warnings:
du -sh /path/to/dir 2>/dev/null

du command hangs or takes hours on root (/) directory

Root Cause: The command is traversing into virtual filesystems (/proc, /sys), infinite symlinks, or massive network mounts (NFS).

Resolution: Always add the -x (--one-file-system) flag to restrict traversal strictly to the local physical filesystem.

sudo du -xh --max-depth=1 /

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
df (disk free) queries filesystem superblocks to report total, used, and available space per mounted partition instantly. du (disk usage) recursively traverses directory trees, inspecting individual file inodes to calculate the actual storage space consumed by specific folders.
ls reports apparent size (the number of bytes in the file), whereas du reports physical disk blocks allocated. Because filesystems allocate storage in fixed blocks (typically 4096 bytes), a 1-byte file still occupies a full 4KB block on disk, which du reflects.
Install and use ncdu (NCurses Disk Usage): sudo apt install ncdu; ncdu /var. ncdu scans the directory and provides an interactive terminal browser with arrow key navigation, sorting, and built-in file deletion.
Use the command: du -h --max-depth=1 /path | sort -hr. The sort -h flag understands human-readable suffixes (G, M, K) and -r reverses the order so the largest directories appear at the top.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout