Automate Your System Updates with a Custom Bash Script

Published on: By: VAZID Category: Linux

Keeping your Linux system up-to-date is crucial for security and performance, but it can be tedious to manually update your system regularly. In this blog, I’ll show you how to automate this process with a custom Bash script that updates your system, logs the changes, and even manages the log files for you.

This is a Bash Script you can use to update your system and take logs.

                    
#!/bin/bash

# Define constants and configurations
RELEASE_FILE="/etc/os-release"
LOG_DIR="/var/log/system_updates"
DATE=$(date '+%Y-%m%d_%H-%M-%S')
LOG_FILE="$LOG_DIR/system_update_$DATE.log"

# Function to log messages with timestamps
log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | sudo tee -a "$LOG_FILE"
}

# Function to check and create log directory if it doesn't exist
create_log_directory() {
    if [ ! -d "$LOG_DIR" ]; then
        log_message "Log directory does not exist. Creating now..."
        if sudo mkdir -p "$LOG_DIR"; then
            log_message "Log directory created at $LOG_DIR"
        else
            log_message "Failed to create log directory. Exiting."
            exit 1
        fi
    else
        log_message "Log directory already exists: $LOG_DIR"
    fi
}

# Function to check if the script is run as a superuser
check_superuser() {
    if [ "$EUID" -ne 0 ]; then
        echo "This script must be run as root. Please use sudo." >&2
        exit 1
    fi
}

# Function to update Arch Linux systems
update_arch() {
    log_message "--------------Updating Arch Linux---------------"
    if sudo pacman -Syu --noconfirm 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "Arch Linux system updated successfully."
    else
        log_message "Error updating Arch Linux system."
    fi
}

# Function to update APT-based systems
update_apt() {
    log_message "-------------Updating APT-based system-------------"
    if sudo apt update -y 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "APT package list updated successfully."
    else
        log_message "Error updating APT package list."
    fi

    if sudo apt upgrade -y 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "APT packages upgraded successfully."
    else
        log_message "Error upgrading APT packages."
    fi

    if sudo apt dist-upgrade -y 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "APT distribution packages upgraded successfully."
    else
        log_message "Error with APT distribution upgrade."
    fi
}

# Function to update RedHat-based systems
update_redhat() {
    log_message "-------------Updating RedHat-based system------------"
    if sudo dnf update -y 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "DNF update completed successfully."
    else
        log_message "Error during DNF update."
    fi

    if sudo dnf upgrade -y 2>&1 | sudo tee -a "$LOG_FILE"; then
        log_message "DNF upgrade completed successfully."
    else
        log_message "Error during DNF upgrade."
    fi
}

# Main script logic

# Ensure the script is run as root
check_superuser

# Create log directory if it doesn't exist
create_log_directory

log_message "------Starting System Update---------------"

# Identify the OS and perform the update
if grep -qi "arch" "$RELEASE_FILE"; then
    update_arch
elif [ -d /etc/apt ]; then
    update_apt
elif grep -qiE "redhat|fedora|centos" "$RELEASE_FILE"; then
    update_redhat
else
    log_message "Unsupported or unrecognized Linux distribution. Exiting."
    exit 1
fi

log_message "-----------------System update completed-----------------"           

Overview of the Script

The script I created is designed to automatically update system packages on different Linux distributions like Arch, APT-based systems (such as Ubuntu or Debian), and RedHat-based systems (like Fedora and CentOS). It also logs each update, so you have a record of what changes were made.

Detailed Script Breakdown

Identifying the Operating System

The script begins by determining which Linux distribution you're using by checking the contents of /etc/os-release. Depending on the OS, it runs the appropriate update commands.

RELEASE_FILE="/etc/os-release"
LOG_DIR="/var/log/system_updates"

if grep -q "Arch" "$RELEASE_FILE"; then
	echo "--------------Updating Arch Linux---------------"
	sudo pacman -Syu --noconfirm
fi

Logging System Updates

To keep track of the updates, I added a logging mechanism that records each step in a log file stored in /var/log/system_updates/. This ensures you can review what changes were made at any time.

                    
LOG_FILE="$LOG_DIR/system_update_$DATE.log"

log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | sudo tee -a "$LOG_FILE"
}

Setting Up the Script

Moving the Script to /usr/local/bin

After writing the script, you can move it to /usr/local/bin and rename it to something simple, like update, so you can easily run it from the terminal with just one command.

sudo cp update.sh /usr/local/bin/update
sudo chown root:root /usr/local/bin/update
sudo chmod +x /usr/local/bin/update

Automating the Script with Cron

To ensure your system stays updated without manual intervention, you can schedule the script to run daily using a cron job. This example shows how to set it up.

sudo crontab -e

Add the following line:

0 0 * * * /usr/local/bin/update

This command will execute the update script every day at midnight (00:00).

Managing Log Files

Over time, the log files can accumulate, so I included a cron job to automatically delete logs older than 30 days. Here's how you can set it up:

0 0 * * * find /var/log/system_updates/ -type f -mtime +30 -exec rm {} \;

Conclusion

By automating your system updates with this script, you can save time and ensure your Linux system is always secure and up-to-date. Give it a try and let me know how it works for you!
Have any questions or suggestions? Drop a message on email, and don't forget to share this post with your fellow Linux enthusiasts!