How-To: Purge old Ubuntu kernels

Long ago, far away, and right next door, Nick and I discussed Ubuntu and its kernel management.

It all started with my comment that it is wasteful to have all these kernels lying around and never booted into again.

I went searching and did not find much on how to remove those old kernels in an efficient way but eventually I figured it out.

Then Nick wrote it into a script to automate this functionality so I decided to share it with the world. We use this in our vmForge auto-install ISO images after the install has finished and the system updated.

Disclaimer: no warranties, blah blah, you’re on  your own, don’t blame the messenger, always eat your vegetables.

#!/bin/sh

echo Removing old kernels

a=`uname -a | awk '{print $3}' | cut -f "1 2" -d -`
for i in `ls /boot | grep vmlinuz | cut -f "2 3" -d -`; do
  if [ "$i" != "$a" ]; then
    dpkg -l | awk '{print $2}' | grep $i | xargs apt-get -y remove
    dpkg -l | awk '{print $2}' | grep $i | xargs dpkg --purge
    rm -fr /lib/modules/$i-server
  fi
done

And there ya have it.