Shell Script to remove old kernels from Oracle Linux OEL

I am sharing script to remove old linux kernels on RHEL/OEL

Script:

#!/bin/bash

# Define the number of kernels to keep (excluding the current kernel)
NUM_KERNELS_TO_KEEP=2

# Get the list of installed kernel packages
KERNEL_PACKAGES=$(rpm -q kernel | awk '{print $1}')

# Get the number of installed kernels
NUM_KERNELS=$(echo "$KERNEL_PACKAGES" | wc -l)

# Check if the number of kernels is greater than the number to keep
if [ $NUM_KERNELS -gt $NUM_KERNELS_TO_KEEP ]; then
  # Get the list of kernels to remove
  KERNELS_TO_REMOVE=$(echo "$KERNEL_PACKAGES" | tail -n +$(($NUM_KERNELS_TO_KEEP + 1)))

  # Loop through the kernels and remove them
  for KERNEL in $KERNELS_TO_REMOVE; do
    echo "Removing kernel $KERNEL..."
    yum remove -y $KERNEL
  done
else
  echo "No old kernels found or the number of kernels is within the limit."
fi

Set the value of the NUM_KERNELS_TO_KEEP variable to the number of kernels you want to keep (excluding the current kernel).





If you like please follow and comment