Task

Automated System Maintenance

Linux / Shell · 15 min · Practical

Keep your Linux servers clean, optimized, and healthy automatically. This script safely purges stale packages, drops memory caches, rotates old logs, and reclaims dead Docker resources.

The Complete Bash Script

Save this file as maintenance.sh and make it executable with chmod +x maintenance.sh.

maintenance.sh
#!/bin/bash

LOGFILE="/var/log/last-7days-maintenance.log"

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

# 2. Logging
exec > >(tee -a $LOGFILE) 2>&1

# 3. Detect OS and cleanup packages
if grep -qi "ubuntu" /etc/os-release; then
    echo "Ubuntu detected - cleaning packages"
    apt update -y
    apt autoremove --purge -y
    apt autoclean -y
    apt clean
elif grep -qiE "rhel|centos|rocky|alma" /etc/os-release; then
    echo "RHEL-based OS detected - cleaning packages"
    yum update -y
    yum autoremove -y
    yum clean all
fi

# 4. Clear memory cache safely
echo "Clearing RAM cache"
sync
echo 3 > /proc/sys/vm/drop_caches

# 5. Clean old temp files (older than 7 days)
echo "Cleaning temp files older than 7 days"
find /tmp -type f -mtime +7 -delete
find /var/tmp -type f -mtime +7 -delete

# 6. Vacuum journal logs
echo "Cleaning journal logs older than 7 days"
journalctl --vacuum-time=7d

# 7. Restart systemd daemon safely
echo "Reloading systemd daemon"
systemctl daemon-reexec

# 8. Store last 7 days error logs
echo "Saving error logs"
journalctl -p err --since "7 days ago" --no-pager > /var/log/last-7days-errors.log

# 9. Docker cleanup
if command -v docker &> /dev/null; then
    echo "Cleaning Docker resources older than 30 days"
    docker container prune --filter "until=720h" -f
    docker image prune -a --filter "until=720h" -f
    docker network prune --filter "until=720h" -f
    docker volume prune -f
    docker builder prune --filter "until=720h" -f
else
    echo "Docker not installed, skipping"
fi

How the Script Works

1. Execution & Foundation

  • root check if [ "$EUID" -ne 0 ] ensures the script aborts immediately if not run as root. Root privileges are mandatory for cache clearing and package managers.
  • logging exec > >(tee -a $LOGFILE) 2>&1 forces all stdout and stderr from the script into a log file while simultaneously keeping it visible in the terminal.
  • os detect Reads /etc/os-release to determine whether to use apt (Ubuntu/Debian) or yum (RHEL/CentOS) to safely update and auto-remove orphaned packages.

2. System Health & Storage

  • ram cache sync flushes pending writes to disk, then drop_caches tells the kernel to release clean caches, dentries, and inodes, improving memory availability.
  • temp files The find command seeks out and permanently deletes files in /tmp and /var/tmp that haven't been modified in over 7 days.
  • journalctl --vacuum-time=7d trims bloated system logs, freeing up critical disk space while keeping a week's worth of logs available.

3. Applications & Daemons

  • systemd daemon-reexec safely restarts the systemd manager without interrupting running services, clearing its internal state.
  • error dump Queries systemd for strictly High-Priority Error logs (-p err) over the last 7 days and outputs them to a flat file for easy troubleshooting.
  • docker purge Checks if Docker exists. If so, it aggressively prunes dead containers, images, volumes, and build cache older than 720 hours (30 days).

Schedule the Maintenance

You don't want to run this manually. By registering the script into the root crontab, the server will clean itself silently in the background.

terminal

# 1. Open the root crontab editor
$ crontab -e

# 2. Add this line at the bottom
$ 0 2 * * 0 /root/maintenance.sh
↳ Executes every Sunday (0) at 2:00 AM