Back to Resources

Level Verified

Linux Disk Cleanup Script

Created by

Level

Type

Script

Category

Maintenance

Platforms
WindowsApple iOSLinux

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.

Description

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.

Script

#!/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"

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

FAQ

  • 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.

Included with this Script:

Below is a list of what you can expect to find when importing this Script.

Script details:

The following data and settings will be imported with your script.

Script Name

Linux - Cleanup Disk Space

Description

This script thoroughly cleans system files to free up disk space. It removes temporary files, old logs, package manager caches, journald logs, Docker artifacts, and Kubernetes logs. Additionally, it logs the cleanup process and provides a summary of the total space saved.

Language

Bash

Timeout (In Seconds)

300

Run As

Local system

Import into Level

Related resources

Explore more automations, scripts, and policies to further enhance your IT operations.

View all resources