How to remove old Kernel and header versions.

While trying to update a server today I was receiving a dpkg error warning that the disk was full.

A simple cmd will show disk usage

df -l

This showed that my \boot partition was full!

We need to browse to the partition

cd /boot

Then list the contents

ls

This showed it was full of old kernels and header versions, so how do we remove these without breaking everything? This is how I did it.

First we need to find out which version we are using.

uname -r

whatever version you are using, DO NOT REMOVE IT!

Let’s see what other versions dpkg thinks we have.

 dpkg -l | tail -n +6 | grep -E 'linux-image-[0-9]+' | grep -Fv $(uname -r) 

Now we can see what we have we can remove them, but note you should only remove those labelled ‘ii’ in the output. If they are labelled ‘iU’ DO NOT remove them.

ALWAYS make a backup/snapshot before making major changes!!!!!

To remove a kernel image we use;

 sudo dpkg --purge linux-image-4.4.0-142-generic 

In my example I state version “4.4.0-143” but yours will be dependent on which versions show in the output in the previous step. I however received an error stating a dpkg error.

No worries we know we can remove the version as it is not in use so we should be able to remove the dependency

We run the same cmd but this time against the dependency.

 sudo dpkg --purge linux-image-extra-4.4.0-142-generic 

Excellent, let’s try and remove the kernel again.

Excellent, so we just repeat the steps for all the versions and their dependencies

I tried to run ‘apt-get update’ but it shows the headers are still installed.

So I used the same cmd to remove the headers

sudo dpkg --purge linux-headers-4.4.0-142-generic 

Then tried running “apt-get update” again, but when trying to install updates I received the same output that headers are still installed. I tried to purge again but get a dpkg error that the header is not installed. Hmmmm.

I’m not a fan of “autoremove” as I have broken many an installation using this cmd incorrectly. However as I have manually removed these I’m pretty confident it’ll be OK. I created another snapshot just to be sure, then went for it.

sudo apt autoremove 

No errors, so I updated Grub next

sudo update grub 

Again no errors and able to update without issues. Phew. No to carry on with what I was trying to do in the first place.