Operations 10 min read

Automate Linux Disk Cleanup with a Powerful Bash Script

This guide presents a comprehensive Bash script that safely automates Linux system‑disk cleanup by removing APT caches, temporary files, old kernels, logs, browser caches, Snap packages, Docker data, and locating large files, while providing before‑and‑after disk usage reports.

Dunmao Tech Hub
Dunmao Tech Hub
Dunmao Tech Hub
Automate Linux Disk Cleanup with a Powerful Bash Script

Introduction

As a Linux user, running out of disk space is common due to accumulated caches, old kernels, and logs. This article provides a Bash script that automates system‑disk cleanup, freeing space safely.

Script Overview

The script groups cleaning tasks into four categories: basic cleanup, system maintenance, application cleanup, and space analysis.

Basic Cleanup

APT cache removal

Temporary files in /tmp and /var/tmp

Thumbnail cache removal

System Maintenance

Safe removal of old kernels while keeping the current one

Log rotation: compress and delete logs older than 7 days

Application Cleanup

Browser cache removal for Chrome and Firefox

Removal of obsolete Snap packages

Docker unused data cleanup

Space Analysis

Find large files (>100 MB)

Show disk usage before and after cleaning

Key Implementation Details

1️⃣ Permission Check

if [ "$(id -u)" -ne 0 ]; then
    echo -e "${YELLOW}Warning: Run as root for full cleanup${NC}"
    read -p "Continue? (y/n) " -n 1 -r
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

2️⃣ Old Kernel Cleanup

current_kernel=$(uname -r)
sudo apt-get purge $(dpkg -l linux-{image,headers}-* | awk '/^ii/{print $2}' \
    | grep -vE "$current_kernel|$(echo $current_kernel | sed 's/-generic//')" | sort -u)

3️⃣ Log Management

find /var/log -type f -name "*.log" -mtime +7 -exec rm -f {} \;
journalctl --vacuum-time=7d

4️⃣ Browser Cache Cleanup

for user in /home/*; do
    [ -d "$user" ] || continue
    echo "Cleaning user: $(basename "$user")"
    [ -d "$user/.cache/google-chrome/Default/Cache" ] && rm -rf "$user/.cache/google-chrome/Default/Cache"
    [ -d "$user/.cache/mozilla/firefox" ] && find "$user/.cache/mozilla/firefox" -name "cache2" -exec rm -rf {} +
 done

Additional Cleanups

Snap packages and Docker data are removed only after confirming their presence and user consent.

Snap Cleanup

if command -v snap &>/dev/null; then
    LANG=C snap list --all | awk '/disabled/{print $1, $3}' |
    while read -r snapname revision; do
        sudo snap remove "$snapname" --revision="$revision"
    done
fi

Docker Cleanup

if command -v docker &>/dev/null; then
    read -p "Delete all unused Docker data? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker system prune -af
    fi
fi

Large File Detection

find / -xdev -type f -size +100M -exec ls -lh {} \; 2>/dev/null |
    sort -k5 -rh | head -n 20

Full Script

#!/bin/bash

# Linux system disk cleanup script
# Functions: clean caches, old kernels, logs, etc.

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# Check for root
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${YELLOW}Warning: Run as root for full cleanup${NC}"
    read -p "Continue? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Show current disk usage
echo -e "
${GREEN}=== Current Disk Usage ===${NC}"
df -h /

# Clean APT cache
echo -e "
${GREEN}=== Clean APT Cache ===${NC}"
sudo apt-get clean
sudo apt-get autoclean

# Remove unnecessary packages
echo -e "
${GREEN}=== Autoremove Unused Packages ===${NC}"
sudo apt-get autoremove --purge

# Clean old kernels
echo -e "
${GREEN}=== Clean Old Kernels ===${NC}"
current_kernel=$(uname -r)
echo "Current kernel: $current_kernel"
sudo apt-get purge $(dpkg -l linux-{image,headers}-* | awk '/^ii/{print $2}' \
    | grep -vE "$current_kernel|$(echo $current_kernel | sed 's/-generic//')" | sort -u)

# Clean logs (keep last 7 days)
echo -e "
${GREEN}=== Clean Log Files ===${NC}"
find /var/log -type f -name "*.log" -mtime +7 -exec rm -f {} \;
journalctl --vacuum-time=7d

# Clean temporary files
echo -e "
${GREEN}=== Clean Temporary Files ===${NC}"
sudo find /tmp -type f -atime +7 -delete
sudo find /var/tmp -type f -atime +14 -delete

# Clean thumbnail cache
echo -e "
${GREEN}=== Clean Thumbnail Cache ===${NC}"
[ -d "$HOME/.cache/thumbnails" ] && rm -rf "$HOME/.cache/thumbnails"/*

# Clean browser caches
echo -e "
${GREEN}=== Clean Browser Caches ===${NC}"
for user in /home/*; do
    [ -d "$user" ] || continue
    echo "Cleaning user: $(basename "$user")"
    [ -d "$user/.cache/google-chrome/Default/Cache" ] && rm -rf "$user/.cache/google-chrome/Default/Cache"
    [ -d "$user/.cache/google-chrome/Default/Code Cache" ] && rm -rf "$user/.cache/google-chrome/Default/Code Cache"
    [ -d "$user/.cache/mozilla/firefox" ] && find "$user/.cache/mozilla/firefox" -name "cache2" -exec rm -rf {} +
 done

# Clean old snap versions
echo -e "
${GREEN}=== Clean Old Snap Versions ===${NC}"
if command -v snap &>/dev/null; then
    LANG=C snap list --all | awk '/disabled/{print $1, $3}' |
    while read -r snapname revision; do
        sudo snap remove "$snapname" --revision="$revision"
    done
fi

# Clean Docker unused data
echo -e "
${GREEN}=== Clean Docker Unused Data ===${NC}"
if command -v docker &>/dev/null; then
    read -p "Delete all unused Docker data? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker system prune -af
    fi
fi

# Find large files (>100M)
echo -e "
${GREEN}=== Find Large Files (>100M) ===${NC}"
find / -xdev -type f -size +100M -exec ls -lh {} \; 2>/dev/null |
    sort -k5 -rh | head -n 20

# Show disk usage after cleaning
echo -e "
${GREEN}=== Disk Usage After Cleanup ===${NC}"
df -h /

echo -e "
${GREEN}Cleanup complete!${NC}"

Usage Recommendations

Run the script monthly to keep the system clean.

Confirm actions for Docker and Snap removals.

Back up important data before cleaning.

Adjust retention periods (e.g., log age) as needed.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AutomationLinuxSystem Administrationbashshell scriptDisk Cleanup
Dunmao Tech Hub
Written by

Dunmao Tech Hub

Sharing selected technical articles synced from CSDN. Follow us on CSDN: Dunmao.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.