Files
scripts/bash-scripts/system-clean.sh
2026-03-08 14:54:52 +00:00

98 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
# ============================
# Colours
# ============================
RED="\e[31m"
GREEN="\e[32m"
YELLOW="\e[33m"
BLUE="\e[34m"
MAGENTA="\e[35m"
CYAN="\e[36m"
BOLD="\e[1m"
RESET="\e[0m"
line() {
echo -e "${CYAN}────────────────────────────────────────────────────────${RESET}"
}
# ============================
# DATE HEADER
# ============================
echo -e "${BOLD}${MAGENTA}=== System Clean Run: $(date '+%Y-%m-%d %H:%M:%S') ===${RESET}"
line
echo -e "${BOLD}${GREEN}=== Ubuntu System Cleanup ===${RESET}"
line
# ============================
# 1. Clean APT cache
# ============================
echo -y >/dev/null 2>&1
sudo apt autoclean -y >/dev/null 2>&1
sudo apt clean -y >/dev/null 2>&1
echo -e "${GREEN}✓ APT cache cleaned.${RESET}"
line
# ============================
# 2. Journal logs cleanup
# ============================
echo -e "${BOLD}${BLUE}[2/8] Cleaning journal logs (keeping 100MB)...${RESET}"
echo -e "${CYAN}Current journal disk usage:${RESET}"
journalctl --disk-usage || true
sudo journalctl --vacuum-size=100M >/dev/null 2>&1
echo -e "${GREEN}✓ Journal logs vacuumed.${RESET}"
line
# ============================
# Remove old logs
# ============================
echo -e "${BOLD}${BLUE}[3/8] Removing rotated logs...${RESET}"
sudo find /var/log -type f -name "*.gz" -delete
sudo find /var/log -type f -name "*.1" -delete
echo -e "${GREEN}✓ Old log archives removed.${RESET}"
line
# ============================
# 4. Clear /tmp and /var/tmp
# ============================
echo -e "${BOLD}${BLUE}[4/8] Clearing temp directories...${RESET}"
sudo rm -rf /tmp/* /var/tmp/*
echo -e "${GREEN}✓ Temporary files cleared.${RESET}"
line
# ============================
# 5. Free RAM (cache)
# ============================
echo -e "${BOLD}${BLUE}[5/8] Dropping filesystem caches (safe)...${RESET}"
sync
echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null
echo -e "${GREEN}✓ RAM caches dropped.${RESET}"
line
# ============================
# 6. Reset failed services
# ============================
echo -e "${BOLD}${BLUE}[6/8] Resetting failed systemd units...${RESET}"
sudo systemctl reset-failed >/dev/null 2>&1
echo -e "${GREEN}✓ Failed units reset.${RESET}"
line
# ============================
# 7. Disk usage snapshot
# ============================
echo -e "${BOLD}${BLUE}[7/8] Largest directories under / ...${RESET}"
du -h --max-depth=1 / 2>/dev/null | sort -hr | head -n 10
echo -e "${GREEN}✓ Disk usage shown.${RESET}"
line
# ============================
# 8. CPU usage snapshot
# ============================
echo -e "${BOLD}${BLUE}[8/8] Top CPU-consuming processes...${RESET}"
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head
echo -e "${GREEN}✓ CPU snapshot shown.${RESET}"
line
echo -e "${BOLD}${GREEN}=== Cleanup Complete! ===${RESET}"