Successfully tested on Ubuntu Server 12.04 LTS 64-bit

In a recent post, I explained how important it is to keep your operating system up to date. If you followed my advices, you may have noticed that Ubuntu’s package manager does not delete any old kernel when upgrading to a new one. It’s on purpose, just to have a known good kernel around in case the upgrade fails. While this is a rather reassuring behavior, you could also want to get rid of these old kernels (to free up some space on your hard disk for example). Let’s see how.

Before doing any cleaning, first write down your current kernel release. You’ll find it by running:

uname -r

 
Next, simulate the old kernels removal:

dpkg -l linux-* | awk '/^ii/{ print $2}' | grep -v -e `uname -r | cut -f1,2 -d"-"` | grep -e [0-9] | xargs sudo apt-get --dry-run remove

 
Here, the –dry-run parameter allows to see the events that would occur during real removal but no change is actually done to the system. Check all the informations displayed on screen to make sure there was no error and verify that your current kernel release was not listed anywhere.

If everything looks fine, you can run the command for real:

dpkg -l linux-* | awk '/^ii/{ print $2}' | grep -v -e `uname -r | cut -f1,2 -d"-"` | grep -e [0-9] | xargs sudo apt-get -y purge

 
Old kernels are history now.

That’s all Folks!


For further reading, see the Ubuntu wiki to understand why this removal is not so easy to automate.

Advertisements