Invisible Automatic Update & Cleanup Script at Boot (using Cron)

Hi everyone,

I wanted to share a clean and completely automated script I set up on Zorin OS Lite to handle system updates (APT & Flatpak) and disk cleanup automatically at startup.

Why use this?
Many automation scripts trigger an annoying password prompt or fail silently in the background because of sudo restrictions. By using system Cron, this script runs invisibly with root privileges right after your PC turns on, without asking for any password.

Step 1: Create the script

Create a file named cleanup.sh in your home folder (/home/USERNAME/cleanup.sh) and paste this code:

#!/bin/bash
# 1. Wait 120 seconds for the network connection to be fully established
sleep 120

# 2. Redirect all outputs to a log file for easy verification
exec > /tmp/cleanup_execution.log 2>&1

echo "=================================================="
echo "      STARTING ZORIN UPDATES AND CLEANUP          "
echo "=================================================="

# 3. Update system packages (APT)
echo -e "\n[1/5] Updating system packages..."
apt-get update
apt-get upgrade -y

# 4. Update Flatpak applications
echo -e "\n[2/5] Updating Flatpak apps..."
flatpak update -y

# 5. Remove useless APT packages and clean cache
echo -e "\n[3/5] Cleaning up system packages..."
apt-get autoremove --purge -y
apt-get clean -y

# 6. Clean system journals (Keep logs under 50M)
echo -e "\n[4/5] Vacuuming system journals..."
journalctl --vacuum-size=50M

# 7. Clean XFCE thumbnail cache
echo -e "\n[5/5] Cleaning XFCE thumbnail cache..."
rm -rf /home/USERNAME/.cache/thumbnails/*

echo "=================================================="
echo "        UPDATES & CLEANUP COMPLETED!              "
echo "=================================================="

Replace USERNAME by your actual name
Make it executable by running this command in your terminal:

chmod +x /home/USERNAME/cleanup.sh

Step 2: Automate it with Cron

Open the root crontab in your terminal:

sudo crontab -e

Go to the very bottom of the file and add this single line:

@reboot nice -n 19 /home/USERNAME/cleanup.sh

(The nice -n 19 ensures the script runs with the lowest CPU priority, so it won't slow down your computer while you start working!)

How to check if it worked?

After a reboot, you can verify that Cron triggered the script by running:

sudo grep -i "cleanup.sh" /var/log/syslog

And you can read the live output of the updates here:

cat /tmp/cleanup_execution.log

Hope this helps Zorin Lite users keep their system fresh and clean effortlessly!
AI-assisted tutorial, please verify critical steps

Two commands of the guide contain your personal username.

1 Like

I am more cautions when running apt-get autoremove and would not personally entertain automating it with a "y". I like to see what is queued for removal and only hit "y" if I am comfortable loosing all the items listed. So that's a manual task for me.

2 Likes

Sorry ! Just put your own username...

/home/username/ should be replace by ~/
and totally agree with @zabadabadoo , all your -y are pretty dangerous !

1 Like

Thanks for the feedback, everyone!

Regarding ~/, since this script is triggered by root's system Cron, ~/ would actually resolve to /root/ instead of the standard user's home directory, causing the thumbnail cleanup to fail. To fix the hardcoded path issue dynamically without breaking Cron, I updated the script to automatically fetch the primary user (UID 1000): PRIMARY_USER=$(id -nu 1000).

Regarding the -y flags, you are totally right. Unattended upgrades can introduce risks if a major package breaks. To make it much safer, I have updated the script to:

  • Use --with-new-pkgs for a safer upgrade path.
  • Simulate and log the autoremove process right before executing it, so users can see exactly what was removed in their logs if they ever need to rollback.
  • Added a desktop notification at the end of the script so you know when the process finishes in the background.

Updated & Safer Script (cleanup.sh)

#!/bin/bash
# 1. Wait 120 seconds for the network connection to be fully established
sleep 120

# 2. Redirect all outputs to a persistent log file
exec > /var/log/cleanup_execution.log 2>&1

echo "=================================================="
echo "      STARTING ZORIN UPDATES AND CLEANUP          "
echo "=================================================="

# 3. Update system packages (APT) safely
echo -e "\n[1/5] Updating system packages..."
apt-get update
apt-get upgrade --with-new-pkgs -y

# 4. Update Flatpak applications (System-wide)
echo -e "\n[2/5] Updating Flatpak apps..."
flatpak update --system -y

# 5. Remove useless APT packages and clean cache
echo -e "\n[3/5] Cleaning up system packages..."
echo "Logging packages scheduled for autoremove:"
apt-get -s autoremove
apt-get autoremove --purge -y
apt-get clean -y

# 6. Clean system journals (Keep logs under 50M)
echo -e "\n[4/5] Vacuuming system journals..."
journalctl --vacuum-size=50M

# 7. Dynamically find primary user and clean XFCE thumbnail cache
echo -e "\n[5/5] Cleaning XFCE thumbnail cache..."
PRIMARY_USER=$(id -nu 1000)

if [ -n "$PRIMARY_USER" ] && [ -d "/home/$PRIMARY_USER/.cache/thumbnails" ]; then
    echo "Cleaning thumbnails for user: $PRIMARY_USER"
    rm -rf /home/$PRIMARY_USER/.cache/thumbnails/*
    
    # 8. Send a desktop notification to the user
    PRIMARY_USER_ID=$(id -u "$PRIMARY_USER")
    DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$PRIMARY_USER_ID/bus" \
    sudo -u "$PRIMARY_USER" notify-send "System Maintenance" "Automated updates and cleanup completed successfully!" --icon=system-software-update
else
    echo "No valid primary user found. Skipping thumbnail cleanup and notification."
fi

echo "=================================================="
echo "        UPDATES & CLEANUP COMPLETED!              "
echo "=================================================="

just because you use root cron and not user cron
Rolling back if you crash the DE with an autoremove will be difficult for a standard user

To make a Suggestion: I would think, it is better to move Your changed Script in Your initial Comment. Some Users might not read until this and simply take the Stuff from Your intial Comment.

You can change Your Comment with clicking on the 3 Dots:

And then on the Pen Icon:

Because of the autoremove, I'm sceptical, too. You changed it, yes. So, there is a Log. But when something essential will be remove and You only have a Black Screen, the Log might not help much.

Also Kernel Updates would require a Reboot to make them run. And there can be other Updates that could require a Reboot.

Don't understand me wrong: I don't want to make Your Script bad. But some Points, I see critical.

1 Like

Of course this is a good idea and a good start to make scripts and understand them, for my part I hate Windows for updates in background without consent, I really prefer to be the actor of my computer not a spectator :wink:

I don't use automatic Updates at all. I let them show me. I look in the Changelog (even when I mostly not understand the technical Aspect in it) and then update the System.

1 Like

Hi everyone!

Following the helpful feedback from the community regarding the risks of automated autoremove tasks triggering within an active session (which could potentially break the Desktop Environment and leave a standard user stranded on a black screen without network access), I have designed a safe, two-step automation system for system maintenance.

How it works:

  • Step 1 (During the session via Cron): The script runs safely in the background to handle APT and Flatpak updates. If any obsolete packages are found, it lists them in a temporary staging file without removing them immediately.
  • Step 2 (At next boot via @reboot): A startup script reads the staged file and safely triggers the purge only after the machine has successfully restarted, avoiding any mid-session environment crashes.

Step-by-Step Installation Guide

1. Create the Main Update Script (cleanup.sh)

This script handles APT updates, Flatpak updates, checks for needed reboots, and stages obsolete packages.

sudo nano /usr/local/bin/cleanup.sh

Paste the following code inside:

#!/bin/bash
# 1. Wait 120 seconds to ensure the network connection is fully established
sleep 120

# 2. Redirect all outputs to a persistent log file
exec > /var/log/cleanup_execution.log 2>&1

echo "=================================================="
echo "      STARTING DEFERRED SYSTEM UPDATES            "
echo "=================================================="

# 3. Update system packages (APT) safely and non-interactively
echo -e "\n[1/4] Updating system packages..."
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get upgrade -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --with-new-pkgs -y

# 4. Update Flatpak applications (System-wide)
echo -e "\n[2/4] Updating Flatpak apps..."
flatpak update --system -y

# 5. Identify obsolete packages WITHOUT removing them (Staging for next boot)
echo -e "\n[3/4] Analyzing obsolete packages..."
PACKAGES_TO_REMOVE=$(apt-get -s autoremove | awk '/^Remv/ {print $2}')

if [ -n "$PACKAGES_TO_REMOVE" ]; then
    # Store the list in a temporary file to be read AT NEXT BOOT
    echo "$PACKAGES_TO_REMOVE" > /var/log/packages_to_cleanup.txt
    echo "The following packages are scheduled for removal at next boot:"
    echo "$PACKAGES_TO_REMOVE"
else
    rm -f /var/log/packages_to_cleanup.txt
    echo "No obsolete packages detected."
fi

# 6. Vacuum system journals (Keep logs under 50M)
echo -e "\n[4/4] Vacuuming system journals..."
journalctl --vacuum-size=50M

# 7. Find primary user and handle desktop notifications
PRIMARY_USER=$(id -nu 1000)
if [ -n "$PRIMARY_USER" ]; then
    PRIMARY_USER_ID=$(id -u "$PRIMARY_USER")
    export DISPLAY=:0
    export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$PRIMARY_USER_ID/bus"
    
    # Check if a REBOOT is required (Kernel, Systemd updates, etc.)
    if [ -f /var/run/reboot-required ]; then
        sudo -u "$PRIMARY_USER" notify-send "System Maintenance" "Updates completed. A reboot is REQUIRED to apply critical modifications." --icon=system-reboot --urgency=critical
    else
        sudo -u "$PRIMARY_USER" notify-send "System Maintenance" "Updates completed. Obsolete files will be cleaned up at next boot." --icon=system-software-update
    fi
fi

echo "=================================================="
echo "             UPDATES COMPLETED!                   "
echo "=================================================="

Save and close (Ctrl+O, Enter, Ctrl+X), then make it executable:

sudo chmod +x /usr/local/bin/cleanup.sh

2. Create the Boot Cleanup Script (cleanup_boot.sh)

This script executes automatically on startup to cleanly purge the staged files.

sudo nano /usr/local/bin/cleanup_boot.sh

Paste the following code inside:

#!/bin/bash
# Wait for core system services to load at boot
sleep 60

LIST_FILE="/var/log/packages_to_cleanup.txt"
BOOT_LOG="/var/log/cleanup_boot.log"

exec > "$BOOT_LOG" 2>&1

echo "--- Boot Cleanup Routine: $(date) ---"

# If the file exists and is not empty, proceed with the removal
if [ -s "$LIST_FILE" ]; then
    PACKAGES=$(cat "$LIST_FILE")
    echo "Removing obsolete packages staged from the last session:"
    echo "$PACKAGES"
    
    # Effective removal
    DEBIAN_FRONTEND=noninteractive apt-get purge -y $PACKAGES
    apt-get autoremove --purge -y
    apt-get clean -y
    
    # Clear the file so it won't run again at next boot
    rm -f "$LIST_FILE"
    echo "Cleanup completed successfully."
else
    echo "No pending cleanup tasks for this boot."
fi

Save and close, then make it executable:

sudo chmod +x /usr/local/bin/cleanup_boot.sh

3. Configure Root's Task Scheduler (crontab)

Open root's crontab configuration:

sudo crontab -e

Scroll to the very bottom of the file and paste this block:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Run the main update script every Sunday at 4:00 AM
0 4 * * 0 /usr/local/bin/cleanup.sh

# Run the deferred cleanup script AT EVERY SYSTEM BOOT
@reboot /usr/local/bin/cleanup_boot.sh

Save and exit. Your automated, community-safe update system is fully active!