Automatic Ubuntu Update Script

Problem

I have several Ubuntu (Linux) computers and systems that run on my home network. Now while I could manually perform updates on each of these, what I decided to do was to create a script that could be placed and each of the computers. Then schedule a cronjob to run nightly or weekly to run the scripts and perform the updates.

Solution

I created the script below of the commands that I would normally run if I was manually updating the computer or server. Full paths of the binaries are included in the script, in case environment variables are not loaded, including the "PATH" variable.

Automatic Restart

When a restart is required after updates are installed, there is a file that is placed in the /var/run directory.

The Script

#!/bin/bash

if [ "$(id -u)" == "0" ]; then
    /bin/echo "$(date) Removing old software"
    /usr/bin/apt-get autoremove --purge -y

    /bin/echo "$(date) Cleaning packages"
    /usr/bin/apt-get clean

    /bin/echo "$(date) Updating repositories"
    /usr/bin/apt-get update

    /bin/echo "$(date) Installing updates"
    /usr/bin/apt-get upgrade -y

    # IF REBOOT FILE HAS BEEN CREATED, THEN DO REBOOT
    if [ -f /var/run/reboot-required ]; then
        /bin/echo "$(date) Reboot is required"
    fi
else
    # THROW ERROR IF NOT RUNNING AS ROOT
    /bin/echo "$(date) ERROR: Must be root to run script."
fi
Updated: 2023-06-03 | Posted: 2016-02-28
Author: Kenny Robinson, @almostengr