3 min read

Automation Guide: Creating a Maintenance Script for Ubuntu

One of the best ways to use Bash scripting is to handle the "boring" stuff. Instead of manually typing update commands every day, you can create a single script that handles the entire maintenance lifecycle of your Ubuntu system.


1. The Goal: A "One-Touch" Maintenance Script

We want a script that performs four critical tasks in order:

  1. Update: Refresh the list of available software.
  2. Upgrade: Actually install the new versions of that software.
  3. Cleanup: Remove "orphaned" files that are no longer needed.
  4. Purge: Empty the local cache of downloaded installer files to save disk space.

2. Writing the Maintenance Script

Open your terminal and create a new file named maintain.sh:

nano maintain.sh

Paste the following code into the editor:

#!/bin/bash

# Ensure the script is running as root (sudo)
if [ "$EUID" -ne 0 ]; then 
  echo "Please run as root (use sudo ./maintain.sh)"
  exit
fi

echo "--- 1/4: Updating package lists... ---"
apt update

echo "--- 2/4: Upgrading system software... ---"
# The -y flag automatically answers 'Yes' to prompts
apt upgrade -y

echo "--- 3/4: Removing unnecessary packages (autoremove)... ---"
apt autoremove -y

echo "--- 4/4: Cleaning up downloaded installer files... ---"
apt autoclean

echo "--- MAINTENANCE COMPLETE ---"

3. Breaking Down the Logic

  • The Root Check ($EUID): This is a safety feature. Since apt requires administrative rights, this block checks if you forgot to type sudo. If you aren't the "root" user, the script stops immediately rather than failing halfway through.
  • The -y Flag: Normally, Ubuntu asks "Do you want to continue? [Y/n]". In a script, this would cause the process to hang forever waiting for you to type. -y automates the "Yes."
  • autoremove: When you uninstall an app, sometimes the "libraries" it used stay behind. This command sweeps them away.
  • autoclean: Every time you update, Ubuntu keeps a copy of the installer (.deb) file. Over months, this can eat up gigabytes of space. This command deletes the old versions.

4. Making it Executable

As we learned in the permissions guide, your new script needs permission to run.

chmod +x maintain.sh

Now, you can run your entire maintenance routine with one command: sudo ./maintain.sh


5. Taking it Further: Automated Scheduling (Cron)

If you don't even want to type the command, you can tell Ubuntu to run this script automatically every night using Cron.

  1. Open the cron scheduler: sudo crontab -e
  2. Add this line at the bottom to run the script every night at 2:00 AM: 0 2 * * * /home/yourusername/maintain.sh

6. Verification: How to Know it Worked

You can check the "History" of your package manager to see what the script changed: less /var/log/apt/history.log

This log keeps a timestamped record of every package the script upgraded or removed.