Removing old linux kernels in Ubuntu

By Eric Lathrop on

I have a recurring problem in Ubuntu where my /boot partition fills up with old kernels, so I can't run updates to get new kernels. I've never really found a satisfactory fix, so I wrote up a bash script to help me.

This script will find any installed kernel/header/module packages for any kernel that's not the current kernel version, and print out a command that uninstalls them. I call the script rmkernels.

#!/bin/bash

set -euo pipefail

VERSION_REGEX='\([0-9]\+.[0-9]\+.[0-9]\+.[0-9]\+-[a-z]\+\)'
CURRENT_VERSION=$(uname -r | sed -e "s/$VERSION_REGEX/\1/")
echo "Current kernel version: $CURRENT_VERSION"

INSTALLED=$(dpkg --list | grep -E -i 'linux-image|linux-headers|linux-modules' | awk '{ print $2 }')

TO_REMOVE=""
while read -r LINE; do
  echo "$LINE" | sed -e "/$VERSION_REGEX/!{q100}" >/dev/null || true
  if [ $? -eq 100 ]; then
    continue
  fi

  INSTALLED_VERSION=$(echo "$LINE" | sed -e "s/.*$VERSION_REGEX/\1/")

  if [ "$INSTALLED_VERSION" == "$CURRENT_VERSION" ]; then
    continue
  fi

  TO_REMOVE+="$LINE "
done <<< "$INSTALLED"

if [ -z "$TO_REMOVE" ]; then
  echo "No old kernels found."
  exit
fi

echo -e "Found old kernels. Run this to remove them:\n"
echo -e "\tsudo apt purge $TO_REMOVE\n"