> ## Documentation Index
> Fetch the complete documentation index at: https://docs.derekdinh.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Resolving Disk Full Errors on Linux and macOS Systems

> Identify and reclaim disk space on Linux and macOS using df, du, find, package cache cleanup, log management, and the macOS Storage Management tool.

A full disk causes cascading failures — applications crash, databases refuse to write, system logs stop recording, and in severe cases the operating system itself becomes unstable. The good news is that the majority of disk-full situations are resolved quickly once you know where to look: package manager caches, rotated log files, and temporary directories frequently account for gigabytes of reclaimable space that accumulated silently over time.

## Identifying the Scope of the Problem

<Steps>
  <Step title="Check Overall Disk Usage with df">
    `df` (disk free) shows the used and available space on every mounted filesystem at a glance. Always start here to confirm which filesystem is full and how severe the situation is.

    ```bash theme={null}
    # Human-readable output for all mounted filesystems:
    df -h

    # Example output:
    # Filesystem      Size  Used Avail Use% Mounted on
    # /dev/sda1        50G   49G  500M  99% /
    # /dev/sda2       200G   80G  120G  40% /home
    # tmpfs           3.9G  1.2M  3.9G   1% /dev/shm

    # Show filesystem type alongside usage:
    df -hT

    # Check only local (non-network) filesystems to avoid slow NFS hangs:
    df -hl
    ```

    <Note>
      A filesystem at **95% or above** should be treated as critically full. Many applications and databases begin failing between 95–100% capacity. Linux reserves 5% of ext4 space for root by default, so a partition may report 100% used while still having \~5% reserved — but this reserve is not available to non-root processes.
    </Note>

    Focus your cleanup effort on the filesystem mounted at `/` (root) if that is the one approaching capacity.
  </Step>

  <Step title="Drill Down with du to Find Disk Hogs">
    Once you know which filesystem is full, use `du` (disk usage) to locate the directories consuming the most space.

    ```bash theme={null}
    # Show the total size of a directory in human-readable format:
    du -sh /var/log/
    # 4.2G    /var/log/

    # List top-level directories, sorted by size (Linux):
    du -h --max-depth=1 /var | sort -rh | head -20

    # Same for macOS (BSD du, slightly different syntax):
    du -hd 1 /var | sort -rh | head -20

    # Quickly find the largest directories system-wide (skip /proc and /sys):
    du -h --exclude=/proc --exclude=/sys --max-depth=3 / 2>/dev/null \
      | sort -rh | head -20
    ```

    <Tip>
      Start at the root (`/`) with `--max-depth=1`, identify the largest directories, then recurse into each one with increasing depth. This top-down approach is much faster than scanning every directory at once.
    </Tip>

    ```bash theme={null}
    # An ncurses-based interactive disk usage browser (install if not present):
    # Linux:
    sudo apt install ncdu   # Debian/Ubuntu
    sudo dnf install ncdu   # Fedora/RHEL

    # macOS:
    brew install ncdu

    # Run it:
    sudo ncdu /
    ```
  </Step>

  <Step title="Find Large Individual Files">
    After identifying large directories with `du`, use `find` to locate individual files above a size threshold anywhere on the system.

    ```bash theme={null}
    # Find files larger than 100 MB on the entire filesystem:
    sudo find / -xdev -size +100M -type f 2>/dev/null

    # Find files larger than 1 GB:
    sudo find / -xdev -size +1G -type f 2>/dev/null

    # Find large files and show their sizes, sorted:
    sudo find / -xdev -size +100M -type f -printf '%s %p\n' 2>/dev/null \
      | sort -rn | head -20 \
      | awk '{printf "%.1f MB\t%s\n", $1/1024/1024, $2}'
    ```

    ```bash theme={null}
    # Search only within /var (common location for logs and caches):
    find /var -size +50M -type f 2>/dev/null | sort

    # Find files that have not been accessed in over 180 days
    # (candidates for archiving or deletion):
    find /var/log -atime +180 -type f 2>/dev/null
    ```

    <Warning>
      Use the `-xdev` flag with `find` when scanning from `/` to prevent it from crossing into other mounted filesystems (e.g., NFS mounts or external drives). Without it, `find` will scan network mounts, which can be extremely slow and misleading.
    </Warning>
  </Step>

  <Step title="Clear Package Manager Caches">
    Package managers download packages to a local cache before installing them. This cache is never automatically purged and can grow to several gigabytes on systems that are updated regularly.

    <Tabs>
      <Tab title="Debian / Ubuntu (apt)">
        ```bash theme={null}
        # Show how much space the apt cache is using:
        du -sh /var/cache/apt/archives/

        # Remove cached packages that are no longer installed:
        sudo apt autoremove

        # Remove all cached package files (.deb files):
        sudo apt clean

        # Less aggressive — remove only outdated cached packages:
        sudo apt autoclean

        # Combined one-liner for maximum reclamation:
        sudo apt autoremove --purge && sudo apt clean
        ```

        <Note>
          `apt autoremove` removes packages that were installed as dependencies but are no longer needed by any installed package. It is safe to run regularly and often reclaims hundreds of megabytes.
        </Note>
      </Tab>

      <Tab title="Fedora / RHEL (dnf)">
        ```bash theme={null}
        # Show cache size:
        du -sh /var/cache/dnf/

        # Remove all cached package data:
        sudo dnf clean all

        # Remove only packages that are no longer needed:
        sudo dnf autoremove

        # Check for and remove old kernel versions (keep the 2 most recent):
        sudo dnf remove --oldinstallonly --setopt installonly_limit=2 kernel
        ```
      </Tab>

      <Tab title="macOS (Homebrew)">
        ```bash theme={null}
        # Show what cleanup would remove without actually removing it:
        brew cleanup --dry-run

        # Remove old versions of installed formulae and stale downloads:
        brew cleanup

        # More aggressive cleanup including downloads older than 30 days:
        brew cleanup --prune=30

        # Show how much space Homebrew is using:
        brew list --versions | wc -l
        du -sh $(brew --cache)
        ```

        <Tip>
          Homebrew also caches downloads in `~/Library/Caches/Homebrew`. Running `brew cleanup` clears this cache automatically. On a typical developer machine this can free 2–5 GB.
        </Tip>
      </Tab>

      <Tab title="Python (pip) / Node (npm)">
        ```bash theme={null}
        # Clear pip's download cache:
        pip cache purge
        # or:
        rm -rf ~/.cache/pip/

        # Clear npm's cache:
        npm cache clean --force
        # Cache location: ~/.npm

        # Check npm cache size:
        du -sh ~/.npm/
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Manage and Rotate Log Files">
    Unrotated or verbose application logs are one of the most common causes of unexpected disk exhaustion, particularly on servers.

    ```bash theme={null}
    # Check total log directory size:
    du -sh /var/log/

    # Find the largest log files:
    find /var/log -type f -name "*.log" -printf '%s %p\n' 2>/dev/null \
      | sort -rn | head -20 \
      | awk '{printf "%.1f MB\t%s\n", $1/1024/1024, $2}'

    # Safely truncate (empty) a log file without deleting it
    # (deleting a file that a process has open does NOT free disk space):
    sudo truncate -s 0 /var/log/syslog
    sudo truncate -s 0 /var/log/apache2/access.log
    ```

    <Warning>
      Never use `rm` to delete a log file that is actively being written to by a running service — the file descriptor remains open and disk space is **not** freed until the service is restarted. Use `truncate -s 0` instead, or restart the service after deletion.
    </Warning>

    **Manage systemd journal logs (Linux):**

    ```bash theme={null}
    # Check journal disk usage:
    journalctl --disk-usage

    # Vacuum journal logs older than 14 days:
    sudo journalctl --vacuum-time=14d

    # Vacuum journal logs to a maximum total size of 500 MB:
    sudo journalctl --vacuum-size=500M

    # Permanently limit journal size in the config:
    sudo nano /etc/systemd/journald.conf
    # Add or modify:
    # SystemMaxUse=500M
    # MaxRetentionSec=2weeks
    sudo systemctl restart systemd-journald
    ```

    **Force log rotation immediately:**

    ```bash theme={null}
    sudo logrotate -f /etc/logrotate.conf
    ```
  </Step>

  <Step title="Clear Temporary Files and Application Caches">
    ```bash theme={null}
    # Clear the system temp directory (safe to remove files older than 1 day):
    sudo find /tmp -maxdepth 1 -atime +1 -exec rm -rf {} \; 2>/dev/null

    # Clear user-level application caches on Linux:
    du -sh ~/.cache/
    rm -rf ~/.cache/thumbnails/   # thumbnail cache — always safe to remove
    rm -rf ~/.cache/google-chrome/Default/Cache/   # Chrome cache

    # Clear Docker images, stopped containers, and build cache
    # (can reclaim tens of GBs on developer workstations):
    docker system df               # show Docker disk usage breakdown
    docker system prune            # remove unused containers, networks, images
    docker system prune -a         # also remove images not referenced by a container
    docker builder prune           # clear build cache only
    ```

    <Tip>
      On machines running Docker, `docker system prune -a` is frequently the single most impactful cleanup action, recovering 10–30 GB on active CI/CD build hosts.
    </Tip>
  </Step>

  <Step title="Use macOS Storage Management (macOS Only)">
    macOS provides a built-in graphical Storage Management tool that categorizes your disk usage and offers system-level optimizations not accessible from the command line.

    1. Click the **Apple menu** → **System Settings** (macOS Ventura or later) or **System Preferences** (earlier).
    2. Select **General** → **Storage** (Ventura) or click **Manage** next to your disk.
    3. The Storage Management window opens and analyzes your drive. Allow it to complete — this takes 30–60 seconds.

    **Built-in optimization options:**

    | Feature                       | What it Does                                                                       |
    | ----------------------------- | ---------------------------------------------------------------------------------- |
    | **Store in iCloud**           | Offloads Desktop, Documents, and Photos to iCloud, keeping only recent files local |
    | **Optimize Storage**          | Removes already-watched iTunes/TV+ movies and TV shows                             |
    | **Empty Trash Automatically** | Deletes items from Trash after 30 days                                             |
    | **Reduce Clutter**            | Shows large files and downloads sorted by size for easy review                     |

    ```bash theme={null}
    # macOS command-line equivalents for scripted cleanup:

    # Empty the Trash from Terminal:
    rm -rf ~/.Trash/*

    # Clear system-level caches (requires restart to rebuild):
    sudo rm -rf /Library/Caches/*
    rm -rf ~/Library/Caches/*

    # Show the largest files in your home directory:
    find ~ -size +100M -type f 2>/dev/null | sort
    ```

    <Note>
      Clearing `~/Library/Caches` on macOS is safe — the OS and applications will rebuild these caches as needed. However, some apps (particularly Xcode and Simulator) store large items here. Check `du -sh ~/Library/Caches/` before and after to confirm the reclaimed space.
    </Note>
  </Step>
</Steps>

***

## Reclaim Space: Priority Checklist

Use this checklist to quickly work through the highest-impact cleanup actions first:

<AccordionGroup>
  <Accordion title="🔴 Quick wins (reclaim space in minutes)">
    ```bash theme={null}
    # 1. Package cache cleanup:
    sudo apt autoremove && sudo apt clean      # Debian/Ubuntu
    brew cleanup --prune=30                    # macOS/Homebrew

    # 2. Journal vacuum:
    sudo journalctl --vacuum-size=500M

    # 3. Temp file cleanup:
    sudo find /tmp -atime +1 -delete 2>/dev/null

    # 4. Docker cleanup (if Docker is installed):
    docker system prune -a
    ```
  </Accordion>

  <Accordion title="🟡 Targeted cleanup (requires review before deleting)">
    ```bash theme={null}
    # 1. Find and review large log files:
    find /var/log -size +100M -type f

    # 2. Find large files in home directories:
    find /home -size +500M -type f 2>/dev/null

    # 3. Review old kernel packages (Linux):
    dpkg --list 'linux-image*' | grep ^ii     # Debian/Ubuntu

    # 4. Identify duplicate or old application data:
    du -sh ~/Downloads/ ~/Desktop/ ~/Documents/
    ```
  </Accordion>

  <Accordion title="🟢 Long-term prevention">
    Set up automated log rotation (`logrotate`), configure `journald` size limits, schedule periodic `apt autoremove` or `brew cleanup` via cron, and enable **iCloud Optimized Storage** on macOS laptops to prevent the disk from filling up again.

    ```bash theme={null}
    # Add a weekly cleanup cron job (Linux):
    echo "0 3 * * 0 root apt autoremove -y && apt clean" \
      | sudo tee /etc/cron.d/weekly-apt-cleanup
    ```
  </Accordion>
</AccordionGroup>

***

## Escalation

<AccordionGroup>
  <Accordion title="Disk is full but du doesn't account for all the space">
    Deleted files held open by running processes can consume space invisibly — `df` shows space as used, but `du` doesn't find the files because they have been deleted from the directory tree.

    ```bash theme={null}
    # Find processes holding deleted files open (Linux):
    sudo lsof +L1 | grep deleted

    # Truncate the file without killing the process:
    sudo truncate -s 0 /proc/<PID>/fd/<FD>
    # or restart the offending service to release the file descriptor.
    ```
  </Accordion>

  <Accordion title="Inode exhaustion (space available but writes fail)">
    A filesystem can run out of inodes (directory entries) while still having free blocks. This produces the same "No space left on device" error.

    ```bash theme={null}
    # Check inode usage across all filesystems:
    df -i

    # If a filesystem shows 100% inode usage, find the directory
    # with the most files (often /var/spool or /tmp):
    find / -xdev -printf '%h\n' 2>/dev/null | sort | uniq -c | sort -rn | head -10
    ```
  </Accordion>

  <Accordion title="Escalation path">
    1. Document the output of `df -h`, `df -i`, and the top output from `du -h --max-depth=3 / 2>/dev/null | sort -rh | head -30`.
    2. If you cannot safely delete enough data to free space, contact your systems administrator or storage team to discuss expanding the volume, adding a new disk, or migrating large directories (e.g., `/var/log`) to a separate mount point.
    3. For cloud instances (AWS EC2, GCP, Azure), submit a request to increase the volume size — this can often be done online without downtime.
  </Accordion>
</AccordionGroup>
