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