Level Verified

Linux Disk Cleanup Script

Automates disk cleanup on Linux by removing cache files, purging old logs, and pruning Docker and Kubernetes leftovers. Reclaims valuable storage, logs its actions, and supports on-demand or scheduled runs through Level’s platform.

Import into Level

Problem overview

Many Linux systems accumulate gigabytes of unnecessary files over time, including obsolete logs, package caches, and container remnants. Manually tracking and removing these files can be labor-intensive, and failing to do so can slow performance, cause system instability, and frustrate users.

Bash 300s timeout Runs as Local system Linux
#!/bin/bash

# This resource is provided as a convenience for Level users. We cannot 
# guarantee it will work in all environments. Please test before deploying 
# to your production environment. We welcome contributions to our community 
# library

# Level Library
# https://level.io/library/script-linux-disk-cleanup

# Create log file
LOG_FILE="/var/log/cleanup_$(date +%Y%m%d_%H%M).log"
TOTAL_SAVED=0

# Ensure running as root
if [ "$EUID" -ne 0 ]; then z
    echo "Please run as root"
    exit 1
fi

log_message() {
    echo "$1" | tee -a "$LOG_FILE"
}

get_size() {
    if [[ -e $1 ]]; then
        du -sk "$1" 2>/dev/null | cut -f1
    else
        echo "0"
    fi
}

delete_safely() {
    local path="$1"
    local desc="$2"
    
    if [[ -e "$path" ]]; then
        local size_before=$(get_size "$path")
        rm -rf "$path" 2>/dev/null
        local freed=$((size_before))
        TOTAL_SAVED=$((TOTAL_SAVED + freed))
        log_message "Cleaned $desc - Freed $((freed/1024)) MB"
    fi
}

log_message "Server cleanup started at $(date)"
log_message "Hostname: $(hostname)"
log_message "Kernel: $(uname -r)"

# Clean various system temp directories
TEMP_PATHS=(
    "/tmp"
    "/var/tmp"
    "/var/cache/apt/archives"  # For Debian/Ubuntu
    "/var/cache/yum"          # For RHEL/CentOS
    "/var/cache/dnf"          # For Fedora
    "/var/log"
)

# Clean each temp location
for path in "${TEMP_PATHS[@]}"; do
    if [[ -d "$path" ]]; then
        log_message "\nCleaning $path..."
        
        # Special handling for package manager caches
        if [[ "$path" == "/var/cache/apt/archives" ]]; then
            apt-get clean 2>/dev/null
            continue
        elif [[ "$path" == "/var/cache/yum" ]]; then
            yum clean all 2>/dev/null
            continue
        elif [[ "$path" == "/var/cache/dnf" ]]; then
            dnf clean all 2>/dev/null
            continue
        fi
        
        # For /var/log, keep recent logs
        if [[ "$path" == "/var/log" ]]; then
            find "$path" -type f -name "*.gz" -mtime +30 -delete 2>/dev/null
            find "$path" -type f -name "*.old" -mtime +30 -delete 2>/dev/null
            find "$path" -type f -name "*.log.*" -mtime +30 -delete 2>/dev/null
            continue
        fi
        
        # For other directories, remove files older than 7 days
        find "$path" -type f -mtime +7 -print0 2>/dev/null | while IFS= read -r -d '' file; do
            # Skip if file is in use
            if lsof "$file" >/dev/null 2>&1; then
                continue
            fi
            delete_safely "$file" "temp file: $(basename "$file")"
        done
    fi
done

# Clean journald logs (if systemd is present)
if command -v journalctl >/dev/null 2>&1; then
    log_message "\nCleaning journald logs..."
    journalctl --vacuum-time=30d >/dev/null 2>&1
fi

# Clean old Docker containers and images (if Docker is installed)
if command -v docker >/dev/null 2>&1; then
    log_message "\nCleaning Docker..."
    docker system prune -af --volumes >/dev/null 2>&1
fi

# Clean old Kubernetes logs (if kubectl is present)
if command -v kubectl >/dev/null 2>&1; then
    log_message "\nCleaning Kubernetes logs..."
    find /var/log/containers -type f -mtime +30 -delete 2>/dev/null
    find /var/log/pods -type f -mtime +30 -delete 2>/dev/null
fi

# Final summary
TOTAL_GB=$(echo "scale=2; $TOTAL_SAVED/1024/1024" | bc)
log_message "\nCleanup completed at $(date)"
log_message "Total space saved: ${TOTAL_GB} GB"
log_message "Log file saved to: $LOG_FILE"

# Report disk usage after cleanup
log_message "\nCurrent disk usage:"
df -h | tee -a "$LOG_FILE"

This script scans crucial system directories to clear stale temporary files, old logs, and redundant package caches. It also includes optional cleanups for journald logs, Docker resources, and Kubernetes logs if installed. Each deleted item is recorded in a log file, and a summary of freed space is provided at the end. You can run this script automatically when disk usage is high by configuring a script-based monitor in Level. Alternatively, integrate it into a scheduled automation within Level to regularly keep storage use in check.

Use cases

  • Quick cleanup on Linux servers with low disk space
  • Routine disk maintenance across multiple client endpoints
  • Automated housekeeping for container-heavy infrastructures
  • Environments requiring consistent system logs rotation and removal

Recommendations

  • Test thoroughly in a non-production setting before rolling out
  • Create a script-based monitor in Level to launch cleanup when disk usage exceeds a threshold
  • Set up a scheduled trigger in Level to maintain ongoing disk cleanliness
  • Verify your /var/log policies before deleting older log files

Frequently asked questions.

Will this script remove critical system files?

It targets known temp or cache directories, and keeps recent logs to protect essential data. Test in a controlled environment first to confirm it aligns with your use-case.

Does it handle locked or active files?

Yes. The script checks for open files using lsof and skips those in use.

What if I don’t use Docker or Kubernetes?

Those steps will simply be skipped if Docker or kubectl aren’t installed on the system.

How often should I run this script?

It depends on your disk usage patterns. You can schedule it weekly or monthly, or tie it to disk space alerts for on-demand cleanup.

Where can I find the cleanup log after it runs?

The script saves a timestamped log in /var/log for easy review of deleted files and total space reclaimed.

Ready when you are.

No credit card. No sales call. Just sign up and start managing.