Removing old kernels in Debian or Ubuntu

When one installs kernels they need to get upgraded every once in a while and while normal packages are removed once they are upgraded, kernels are not. You can install a newer kernel and the old will still be present. The reason for this simple, if the updated kernel is not working correctly you can use the previous kernel to boot your machine and continue working. However, when you have done this several times there will be a huge list of kernels and these need to be removed every once in a while. I made a script once that removes obsolete kernels, but it was specific to Ubuntu only and I needed something similar for Debian. So I completely rewrote the script and this is the end result.

Include this in your .bashrc (or create a script for it) and use the following functions to remove kernels which are no longer needed (other then your running kernel). It will also remove any kernel header packages. You will not delete meta-packages for kernels, eg linux-image-generic or linux-image-generic-pae unless the kernel you are running is not the most recent one. The script looks at the dependencies (including reversed) to avoid such deletions. I’ve tested it on Debian and Ubuntu. In case of bugs, let me know!