#!/bin/bash # This script installs the latest Python version and pip on Ubuntu 22.04 LTS # Function to check for errors check_error() { if [ $? -ne 0 ]; then echo "Error: $1" exit 1 fi } # Step 1: Update the package list echo "Updating package list..." sudo apt update check_error "Failed to update package list." # Step 2: Install prerequisite packages echo "Installing prerequisite packages..." sudo apt install -y software-properties-common curl check_error "Failed to install prerequisites." # Step 3: Add the deadsnakes PPA echo "Adding deadsnakes PPA for latest Python versions..." sudo add-apt-repository ppa:deadsnakes/ppa -y check_error "Failed to add deadsnakes PPA." # Step 4: Update the package list again after adding the PPA echo "Updating package list after adding PPA..." sudo apt update check_error "Failed to update package list after adding PPA." # Step 5: Install the latest Python version (e.g., Python 3.11) PYTHON_VERSION=3.11 echo "Installing Python $PYTHON_VERSION..." sudo apt install -y python${PYTHON_VERSION} check_error "Failed to install Python $PYTHON_VERSION." # Step 6: Set Python 3.x as the default python3 version echo "Setting Python $PYTHON_VERSION as the default python3..." sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python${PYTHON_VERSION} 1 check_error "Failed to set Python $PYTHON_VERSION as the default python3." # Step 7: Install pip echo "Installing pip for Python $PYTHON_VERSION..." sudo apt install -y python3-pip check_error "Failed to install pip." # If pip is not installed for the latest version, use get-pip.py if ! command -v pip3 &> /dev/null; then echo "Pip not found, downloading get-pip.py..." curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py sudo python${PYTHON_VERSION} get-pip.py check_error "Failed to install pip using get-pip.py." rm get-pip.py fi # Step 8: Verify installation echo "Verifying Python and pip installation..." python3 --version pip3 --version echo "Python and pip installation completed successfully!"