BASH

Automate System Package Updates

A robust Bash script to efficiently update and upgrade system packages on Debian/Ubuntu and RHEL/CentOS distributions, ensuring your servers are up-to-date and secure.

#!/bin/bash

# This script updates and upgrades system packages based on the detected OS.

if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
else
    echo "Cannot detect OS. Exiting."
    exit 1
fi

echo "Detected OS: $OS"

case "$OS" in
    ubuntu|debian)
        echo "Updating Ubuntu/Debian packages..."
        sudo apt update -y && sudo apt upgrade -y
        sudo apt autoremove -y
        echo "Ubuntu/Debian update complete."
        ;;
    centos|rhel|fedora)
        echo "Updating RHEL/CentOS/Fedora packages..."
        sudo yum check-update || sudo dnf check-update # Check both yum and dnf
        sudo yum update -y || sudo dnf update -y
        sudo yum autoremove -y || sudo dnf autoremove -y # For yum-based systems
        echo "RHEL/CentOS/Fedora update complete."
        ;;
    *)
        echo "Unsupported OS: $OS. Manual update required."
        exit 1
        ;;
esac

exit 0
How it works: This Bash script automates the process of updating and upgrading system packages. It first detects the operating system using `/etc/os-release`. Based on whether it's a Debian/Ubuntu or RHEL/CentOS/Fedora distribution, it executes the appropriate package manager commands (`apt` for Debian/Ubuntu, `yum` or `dnf` for RHEL/CentOS/Fedora) to update package lists, upgrade installed packages, and remove unused dependencies. This ensures your server environments remain secure and have the latest software.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs