Freepoorman
Active Member
Bash:
#!/bin/bash
# Function to handle errors
handle_error() {
echo "An error occurred: $1"
read -p "Press Enter to exit."
exit 1
}
# Trap errors
trap 'handle_error "$BASH_COMMAND"' ERR
# Logging directory
LOG_DIR="/home/erik/Documents/Update_logs"
# Ensure the log directory exists
mkdir -p "$LOG_DIR"
# Rotate logs to keep a maximum of 5 logs
rotate_logs() {
local log_dir=$1
local max_logs=5
# Find and remove older log files
find "$log_dir" -name "*.log" -type f -mtime +$max_logs -exec rm -f {} \;
}
# Rotate logs before creating a new one
rotate_logs "$LOG_DIR"
# Logging
LOG_FILE="$LOG_DIR/system_update_$(date +%Y%m%d%H%M%S).log"
exec &> >(tee -a "$LOG_FILE")
# Extend sudo timeout
sudo -v
echo -e "Reloading system manager configuration before performing full system update and cleanup..."
sudo systemctl daemon-reload
echo -e "\nUpdating package lists..."
sudo apt-get update || handle_error "Failed to update package lists"
echo -e "\nUpgrading all installed packages..."
sudo apt-get dist-upgrade -y || handle_error "Failed to upgrade packages"
echo -e "\nInstalling security updates not included in the regular upgrade..."
SECURITY_UPDATES=$(apt-get -s upgrade | awk '/^Inst/ { if ($4 !~ /^(.*-security|security)$/) next; print $2 }')
echo "Security updates to be installed: $SECURITY_UPDATES"
if [ -n "$SECURITY_UPDATES" ]; then
sudo apt-get install --only-upgrade $SECURITY_UPDATES -y || handle_error "Failed to install security updates"
else
echo "No security updates found."
fi
echo -e "\nInstalling recommended drivers..."
sudo ubuntu-drivers autoinstall || handle_error "Failed to install recommended drivers"
echo -e "\nRemoving unnecessary packages..."
sudo apt-get autoremove -y || handle_error "Failed to remove unnecessary packages"
echo -e "\nCleaning up package cache..."
sudo apt-get clean || handle_error "Failed to clean package cache"
echo -e "\nPurging unnecessary packages and their configuration files..."
sudo apt-get autoremove --purge -y || handle_error "Failed to purge unnecessary packages"
echo -e "\nCleaning up journal logs..."
sudo journalctl --vacuum-time=2d || handle_error "Failed to clean journal logs"
echo -e "\nUpdating Snap packages..."
sudo snap refresh || handle_error "Failed to update Snap packages"
echo -e "\nUpdating Flatpak packages..."
flatpak update -y || handle_error "Failed to update Flatpak packages"
echo -e "\nClearing the Linux cache..."
sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches' || handle_error "Failed to clear Linux cache"
echo -e "\nSystem update and cleanup completed."
# Prompt for reboot or exit
read -p "Press [Enter] to reboot or [Esc] to exit the terminal..." -s -n 1 key
if [[ $key = $'\e' ]]; then
echo "Exiting the terminal..."
else
echo "Rebooting the system..."
sudo reboot
fi
Feel free to make suggestions and criticisms. I'd appreciate it very much