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:

    1. # Show capacity, used, available, and usage rate for each mount point
    2. df -h
    3. # Check inode usage to investigate scenarios with massive numbers of small files
    4. df -i
    5. # Target a specific mount point to avoid noise from other partitions
    6. df -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:

    1. # Show first-level directory usage under root, sorted in descending order
    2. du -sh /* 2>/dev/null | sort -rh | head -10
    3. # Drill further into a suspicious directory, such as the log directory
    4. du -ah /var/log 2>/dev/null | sort -rh | head -20

    Pinpoint Files by Dimension

    1. # Find regular files larger than 100MB in the current directory
    2. find . -type f -size +100M -exec ls -lh {} \;
    3. # Find files larger than 1GB across the disk, suppressing permission errors
    4. find / -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:

    1. #!/bin/bash
    2. echo "=== Mount points with usage above 80% ==="
    3. df -h | awk 'NR>1 && int($5) > 80 {print $0}'
    4. echo -e "\n=== Directories with the highest usage ==="
    5. du -h / 2>/dev/null | sort -hr | head -10
    6. echo -e "\n=== Files with the highest usage ==="
    7. 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:

    1. # Delete log files older than 7 days
    2. find /var/log -name "*.log" -mtime +7 -delete
    3. # Compress logs older than 3 days to reduce usage
    4. find /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:

    1. # Safely clear an active log while keeping the file and its handle
    2. : > /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:

    1. # Check usage of temporary and cache directories
    2. du -sh /tmp /var/tmp /var/cache/* 2>/dev/null
    3. # Clean temporary files older than one day to avoid affecting active jobs
    4. find /tmp -type f -mtime +1 -delete
    5. find /var/tmp -type f -mtime +1 -delete
    6. # Clean system package caches (commands differ slightly by distribution)
    7. # RPM-based distributions
    8. yum clean all
    9. # DEB-based distributions
    10. apt-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:

    1. #!/bin/bash
    2. # disk_cleanup.sh — Tiered disk space inspection and cleanup
    3. LOG_FILE="/var/log/disk_cleanup.log"
    4. THRESHOLD=80
    5. log_message() {
    6. echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
    7. }
    8. check_disk_usage() {
    9. local usage
    10. usage=$(df / | awk 'NR==2 {gsub("%","",$5); print $5}')
    11. if [ "$usage" -gt "$THRESHOLD" ]; then
    12. log_message "Warning: root partition usage is ${usage}%, triggering cleanup"
    13. return 1
    14. fi
    15. log_message "Root partition usage is ${usage}%, status normal"
    16. return 0
    17. }
    18. cleanup_logs() {
    19. find /var/log -name "*.log" -mtime +30 -delete
    20. find /var/log -name "*.log" -mtime +7 -exec gzip {} \;
    21. log_message "Log cleanup completed"
    22. }
    23. cleanup_temp() {
    24. find /tmp -type f -mtime +1 -delete
    25. find /var/tmp -type f -mtime +1 -delete
    26. log_message "Temporary file cleanup completed"
    27. }
    28. if check_disk_usage; then
    29. exit 0
    30. fi
    31. cleanup_logs
    32. cleanup_temp
    33. log_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.