In the world of Linux system administration, efficient disk space management is critical for maintaining system performance, preventing outages, and ensuring smooth operations. Whether you’re a developer, sysadmin, or casual Linux user, the command line offers powerful tools to explore, monitor, and manage disk space. Unlike graphical tools, CLI utilities are lightweight, scriptable, and work across remote servers—making them indispensable for troubleshooting and long-term maintenance. This blog will guide you through fundamental concepts, essential commands, common practices, and best practices for exploring and managing disk space in Linux. By the end, you’ll be equipped to diagnose disk full errors, clean up redundant files, and keep your system’s storage healthy.
Table of Contents
- Fundamental Concepts
- Exploring Disk Space
- Managing Disk Space
- Common Practices
- Best Practices
- Conclusion
- References
Fundamental Concepts
Before diving into commands, let’s clarify key concepts that underpin disk space management in Linux:
Block Devices and Partitions
Linux represents physical storage devices (hard drives, SSDs, USBs) as block devices in the /dev directory. For example:
/dev/sda: First SATA/SCSI disk./dev/nvme0n1: First NVMe SSD.
Devices are divided into partitions (e.g., /dev/sda1, /dev/nvme0n1p2), which act as logical segments for storing data.
Filesystems
Partitions are formatted with filesystems (e.g., ext4, xfs, btrfs), which organize data into files and directories. The filesystem handles how data is written to disk, manages metadata (e.g., permissions, timestamps), and ensures data integrity.
Mount Points
To access a partition’s data, it must be mounted to a directory (called a “mount point”) in the Linux filesystem tree. For example:
- The root filesystem (
/) is mounted on the root directory. - A secondary partition might be mounted at
/homeor/mnt/data.
Use mount or df to list active mount points.
Inodes vs. Blocks
Disk space is managed in two key ways:
- Blocks: Physical storage units for file content (e.g., 4KB blocks). “Out of space” often refers to exhausted blocks.
- Inodes: Metadata structures that track file ownership, permissions, and pointers to data blocks. A filesystem can run out of inodes even if blocks are available (e.g., with millions of small files).
Exploring Disk Space
Let’s start with tools to explore current disk usage. These commands help answer: How much space is used? Which directories/files are taking up space? Are there inode issues?
df: Check Filesystem Usage
The df (disk free) command reports usage for mounted filesystems.
Syntax:
df [options] [mount-point]
Common Options:
-h: Human-readable output (e.g., MB, GB).-T: Show filesystem type (e.g., ext4, xfs).-i: List inode usage (instead of block usage).
Examples:
-
Check all mounted filesystems (human-readable):
df -hOutput:
Filesystem Size Used Avail Use% Mounted on /dev/sda2 200G 80G 110G 43% / /dev/sda1 512M 64M 448M 13% /boot /dev/sdb1 500G 250G 250G 50% /mnt/externalThis shows total size, used space, available space, usage percentage, and mount points.
-
Check inode usage for the root filesystem:
df -i /Output:
Filesystem Inodes IUsed IFree IUse% Mounted on /dev/sda2 12.8M 1.2M 11.6M 9% /Use this to diagnose “no space left” errors caused by inode exhaustion.
du: Analyze Directory/File Sizes
The du (disk usage) command calculates space used by directories or files.
Syntax:
du [options] [directory/file]
Common Options:
-s: Summarize total size for a directory (instead of listing subdirectories).-h: Human-readable output.-a: Include individual files (not just directories).--max-depth=N: Limit recursion toNlevels (e.g.,--max-depth=1for top-level directories).
Examples:
-
Total size of
/home/user:du -sh /home/userOutput:
45G /home/user(45 GB used in the user’s home directory). -
Size of top-level directories in
/(excluding/proc//systo avoid noise):du -sh /* --exclude={/proc,/sys,/dev} 2>/dev/nullOutput:
80G /bin 4.0K /boot 2.5G /etc 120G /home 4.0K /mntThe
2>/dev/nullsuppresses “permission denied” errors for restricted directories. -
List sizes of all files in a directory (with max depth 2):
du -h --max-depth=2 /var/log
lsblk: List Block Devices
The lsblk (list block devices) command provides a tree-like view of disks, partitions, and their mount points.
Syntax:
lsblk [options]
Common Options:
-f: Show filesystem type and UUID.-m: Show permissions (owner/group).
Example:
lsblk -f
Output:
NAME FSTYPE LABEL UUID MOUNTPOINT
sda
├─sda1 vfat 1234-ABCD /boot
└─sda2 ext4 5678-EFGH /
sdb
└─sdb1 xfs IJKL-MNOP /mnt/external
Use this to map physical disks to mount points (e.g., “Which disk is /mnt/external using?“).
ncdu: Interactive Disk Usage Analyzer
ncdu (ncurses disk usage) is an interactive CLI tool for exploring disk usage. It’s not installed by default, but available via package managers (e.g., sudo apt install ncdu or sudo dnf install ncdu).
Syntax:
ncdu [directory]
Example:
Run ncdu / --exclude /proc --exclude /sys to scan the root filesystem (excluding virtual filesystems like /proc).
Navigating ncdu:
- Use arrow keys to move.
- Press
Enterto drill into a directory. - Press
dto delete a file/directory (with confirmation). - Press
qto quit.
Finding Large Files with find
The find command locates files based on size, type, or other criteria. Use it to identify large files hogging space.
Syntax to find large files:
find [directory] -type f -size +[N][unit] 2>/dev/null
-type f: Search for files (not directories).-size +[N][unit]: Files larger thanN(units:k=KB,M=MB,G=GB).2>/dev/null: Suppress permission errors.
Example:
Find all files larger than 1GB on the system:
find / -type f -size +1G 2>/dev/null
Output might include:
/home/user/Videos/movie.mkv
/var/log/syslog.1
Filter results to show sizes and paths:
find / -type f -size +1G -exec du -sh {} \; 2>/dev/null
Output:
8.5G /home/user/Videos/movie.mkv
1.2G /var/log/syslog.1
Managing Disk Space
Once you’ve identified space hogs, the next step is to manage disk space by cleaning up, resizing filesystems, or monitoring usage over time.
Cleaning Up Disk Space
Free up space by removing unnecessary files. Always back up data before deleting!
1. Clean Package Manager Caches
Package managers (e.g., apt, dnf, pacman) store cached installation files.
-
Debian/Ubuntu (
apt):sudo apt clean # Clear all cached packages sudo apt autoremove # Remove unused dependencies -
RHEL/CentOS (
dnf):sudo dnf clean all # Clear cached packages sudo dnf autoremove # Remove unused dependencies
2. Trim Log Files
Log files in /var/log can grow large. Use journalctl (for systemd logs) or logrotate to manage them.
-
Vacuum systemd journal logs (keep only 100MB):
sudo journalctl --vacuum-size=100M -
Delete old log files (e.g.,
.gzarchives older than 30 days):sudo find /var/log -name "*.gz" -mtime +30 -delete
3. Remove Orphaned Files
Use bleachbit (CLI version) to clean temporary files, browser caches, and orphaned data.
Install and run (CLI mode):
sudo apt install bleachbit # Debian/Ubuntu
sudo bleachbit --clean system.cache system.logs # Clean common categories
Resizing Filesystems (Advanced)
Resizing a filesystem (e.g., to add space) is context-dependent (e.g., LVM, physical partitions). Below are simplified examples—always back up data first!
Example 1: Extend an ext4 Filesystem (Non-LVM)
If you added space to a physical partition (e.g., via fdisk), resize the ext4 filesystem with resize2fs:
sudo resize2fs /dev/sda2 # Replace /dev/sda2 with your partition
Example 2: Extend an LVM Logical Volume
If using LVM (Logical Volume Manager), extend the logical volume (LV) and then the filesystem:
# Extend LV by 50GB (replace vg0 and lv_root with your volume group/LV)
sudo lvextend -L +50G /dev/vg0/lv_root
# Resize the ext4 filesystem on the LV
sudo resize2fs /dev/vg0/lv_root
Monitoring Disk Usage Over Time
To track disk usage trends, automate checks with scripts or use monitoring tools.
Simple Monitoring with watch
Run df -h in real time (updates every 2 seconds):
watch -n 2 df -h
Automated Alerts with a Script
Create a cron job to email alerts when usage exceeds a threshold (e.g., 90%).
Example script (check_disk.sh):
#!/bin/bash
THRESHOLD=90
df -h | awk -v threshold="$THRESHOLD" '$5+0 > threshold {print "ALERT: " $0}' | mail -s "Disk Space Alert" [email protected]
Add to crontab (run daily at 2 AM):
0 2 * * * /path/to/check_disk.sh
Common Practices
- Check regularly: Run
df -handdu -sh /homeweekly to catch trends early. - Clean caches: Use
apt cleanordnf cleanmonthly to free up space. - Manage logs: Configure
logrotateto compress/delete old logs automatically. - Audit large files: Use
findorncduquarterly to identify forgotten large files (e.g., old backups).
Best Practices
- Backup before changes: Always back up data before deleting files or resizing filesystems.
- Avoid
rm -rfas root: Accidental deletion of system files (e.g.,rm -rf /) is catastrophic. Usemvto a “trash” directory first if unsure. - Monitor inodes: Use
df -ito check inode usage—small files (e.g., in/tmp) can exhaust inodes even with free space. - Use
sudosparingly: Avoid running disk cleanup commands as root unless necessary (reduces risk of accidental deletion). - Automate safely: Test cleanup scripts in a staging environment before deploying to production.
Conclusion
Mastering Linux CLI disk management tools like df, du, lsblk, and find empowers you to diagnose and resolve storage issues efficiently. By regularly exploring disk usage, cleaning redundant files, and following best practices (e.g., backups, monitoring), you can keep your system running smoothly and avoid “out of space” emergencies.
Practice these commands in a non-critical environment (e.g., a VM) to build confidence, and refer to the references below for deeper dives into specific tools.
References
dfman page: df(1) - Linux manual pageduman page: du(1) - Linux manual pagelsblkman page: lsblk(8) - Linux manual page- Linux Filesystems Guide: Linux Documentation Project
- LVM Guide: Red Hat LVM Documentation
ncduofficial site: ncdu - NCurses Disk Usage