#!/bin/bash set -e # Exit immediately if a command exits with a non-zero status # Get the current kernel version CURRENT_KERNEL=$(uname -r) # Get a list of installed kernels INSTALLED_KERNELS=$(dpkg --list | grep linux-image | awk '{ print $2 }') # Get the two newest kernels NEWEST_KERNEL_1=$(dpkg --list | grep linux-image | awk '{ print $2 }' | sort -r | sed -n '1p') NEWEST_KERNEL_2=$(dpkg --list | grep linux-image | awk '{ print $2 }' | sort -r | sed -n '2p') # Get the list of kernels to remove KERNELS_TO_REMOVE=$(echo "$INSTALLED_KERNELS" | grep -v "$CURRENT_KERNEL\|$NEWEST_KERNEL_1\|$NEWEST_KERNEL_2") # Count the number of kernels to remove NUM_KERNELS_TO_REMOVE=$(echo "$KERNELS_TO_REMOVE" | wc -l) # Print the list of kernels to remove echo "The following kernels will be removed:" echo "$KERNELS_TO_REMOVE" echo "" # Confirm that the user wants to remove the kernels read -p "Are you sure you want to remove $NUM_KERNELS_TO_REMOVE kernels? (y/N) " CONFIRM if [[ $CONFIRM != "y" && $CONFIRM != "Y" ]]; then exit 0 fi # Loop through the list of kernels to remove for KERNEL in $KERNELS_TO_REMOVE do # Remove the kernel sudo apt-get remove -y $KERNEL || echo "Failed to remove $KERNEL." done # Remove leftover packages sudo apt-get autoremove -y || echo "Failed to remove leftover packages." # Cleanup unused kernels sudo apt-get purge -y $(dpkg --list | grep '^rc' | awk '{ print $2 }') || echo "Failed to cleanup unused kernels." echo "Done."