Diagnosing and Cleaning Up Low Disk Space on Linux: A Practical Guide
Low disk space is one of the most frequent alerts in server operations, often leading to failed database writes, crashed processes, and missing logs. This guide walks through a safe workflow: build observability first, clean up with reversible actions, and automate prevention. You will learn how to separate filesystem and inode issues, drill down from mount points to directories and files, identify logs, temporary files, and caches that are safe to remove, and apply a tiered cleanup script with monitoring thresholds. The article also highlights common mistakes and risk controls so you can respond to space alerts with a clear plan instead of risky force deletion.
Diagnosing and Cleaning Up Low Disk Space on Linux: A Practical Guide
In server operations, “low disk space” is one of the most frequent alert types. It can show up as failed database writes, service processes exiting unexpectedly, logs that cannot be written, or even a system that refuses to create new sessions. Many engineers immediately run a force delete, only to remove critical data or an active file handle and turn a single alert into a production incident. The right approach is to establish observability first, perform cleanup actions that can be rolled back, and finally use automation to prevent the problem from recurring. This article follows that path.
1. Diagnose First: Turn Space Usage into Visible Data
Distinguish the Filesystem Layer from the Directory Layer
The first step is to determine whether a partition is full or the inode table is exhausted. The former shows a usage percentage close to 100%, while the latter can leave plenty of free space yet still block new file creation. Basic commands:
# Show capacity, used, available, and usage rate for each mount pointdf -h# Check inode usage to investigate scenarios with massive numbers of small filesdf -i# Target a specific mount point to avoid noise from other partitionsdf -h /home
One important detail: if space is not released immediately after deleting a file, a process is usually still holding the file handle. You can confirm this by querying deleted files that are still in use, then restart or reload the corresponding process to free the space.
Drill Down from Top to Bottom
To locate large directories, follow a “coarse to fine” path and avoid a full-disk scan right away, which creates heavy I/O pressure:
# Show first-level directory usage under root, sorted in descending orderdu -sh /* 2>/dev/null | sort -rh | head -10# Drill further into a suspicious directory, such as the log directorydu -ah /var/log 2>/dev/null | sort -rh | head -20
Pinpoint Files by Dimension
# Find regular files larger than 100MB in the current directoryfind . -type f -size +100M -exec ls -lh {} \;# Find files larger than 1GB across the disk, suppressing permission errorsfind / -type f -size +1G 2>/dev/null -exec ls -lh {} \;
It is a good idea to wrap these commands into an inspection script that outputs a report in a consistent format, making it easy to compare multiple machines side by side:
#!/bin/bashecho "=== Mount points with usage above 80% ==="df -h | awk 'NR>1 && int($5) > 80 {print $0}'echo -e "\n=== Directories with the highest usage ==="du -h / 2>/dev/null | sort -hr | head -10echo -e "\n=== Files with the highest usage ==="find / -type f -size +100M 2>/dev/null | xargs -r ls -lh | sort -k5 -hr | head -10
2. Classify: Identify What Is Safe to Clean
Log Files
Logs are usually the primary cause of space expansion, especially service logs without rotation configured. The strategy is “rotate first, compress next, delete last” rather than clearing files directly:
# Delete log files older than 7 daysfind /var/log -name "*.log" -mtime +7 -delete# Compress logs older than 3 days to reduce usagefind /var/log -name "*.log" -mtime +3 -exec gzip {} \;
For active logs that are still being written, prefer truncation over deletion to avoid breaking the handle:
# Safely clear an active log while keeping the file and its handle: > /var/log/app/current.log
You should also configure log rotation for critical services, defining a per-file size limit, the number of retained copies, and whether compression is enabled, so growth is constrained at the source.
Temporary and Cache Files
Temporary directories and package manager caches hold rebuildable data, so cleanup risk is low, but you still need to exclude files that running processes depend on:
# Check usage of temporary and cache directoriesdu -sh /tmp /var/tmp /var/cache/* 2>/dev/null# Clean temporary files older than one day to avoid affecting active jobsfind /tmp -type f -mtime +1 -deletefind /var/tmp -type f -mtime +1 -delete# Clean system package caches (commands differ slightly by distribution)# RPM-based distributionsyum clean all# DEB-based distributionsapt-get clean
Application and Data Files
Database data files, backup archives, and image layers must not be deleted casually. A safer approach is to move cold data and backups to external storage such as object storage, keeping only recent increments locally. For container environments, clean up stopped instances and dangling image layers, and check whether the container log driver limits single-file size.
3. Harden: Automated Inspection and Tiered Response
A one-time cleanup only solves the immediate problem; long-term stability depends on a mechanism. The script below shows a skeleton for threshold checks and tiered handling:
#!/bin/bash# disk_cleanup.sh — Tiered disk space inspection and cleanupLOG_FILE="/var/log/disk_cleanup.log"THRESHOLD=80log_message() {echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"}check_disk_usage() {local usageusage=$(df / | awk 'NR==2 {gsub("%","",$5); print $5}')if [ "$usage" -gt "$THRESHOLD" ]; thenlog_message "Warning: root partition usage is ${usage}%, triggering cleanup"return 1filog_message "Root partition usage is ${usage}%, status normal"return 0}cleanup_logs() {find /var/log -name "*.log" -mtime +30 -deletefind /var/log -name "*.log" -mtime +7 -exec gzip {} \;log_message "Log cleanup completed"}cleanup_temp() {find /tmp -type f -mtime +1 -deletefind /var/tmp -type f -mtime +1 -deletelog_message "Temporary file cleanup completed"}if check_disk_usage; thenexit 0ficleanup_logscleanup_templog_message "Inspection round finished, current usage: $(df -h / | awk 'NR==2 {print $5}')"
Recommended practices include: schedule the script during off-peak business hours; report usage rate, inode usage rate, and directory growth to your monitoring and alerting system with two thresholds, a 70% warning and an 85% critical level; and retain operation logs for cleanup actions so every deletion is traceable.
4. Common Mistakes and Risk Controls
- Do not delete files still held by a process, or space will not be released; use truncation or restart the process instead.
- Do not ignore inode bottlenecks; with massive small files, writes can fail even when space is available.
- Do not run full-disk scans during business peaks; high I/O slows online services, so throttle or schedule off-peak.
- Do not use force delete without confirmation; scripts should print the deletion list first and run it only after confirmation.
- Do not treat symptoms only; after cleanup, complete log rotation, capacity planning, and growth trend monitoring.
5. Summary
The essence of disk space governance is a closed loop: use visualization to locate the problem, classification to separate deletable from non-deletable data, reversible actions to perform cleanup, and automated inspection plus alerting to lock in the results. In cloud environments, you can also use object storage for cold data, a log service for centralized log management, and a monitoring and alerting system for early warning, shifting from reactive firefighting to proactive capacity operations. With this method, you will have a clear order of response when a space alert fires, instead of pressing delete and hoping for the best.
