Purging outdated kernels on systems with unattended-upgrades

Whenever I install a production system/server I tend to enable full automatic updating, because
it's usually better that something breaks because of a failed update rather than leaving a production machine unpatched; and if you pick a rather stable distribution (Centos or Ubuntu LTS are good examples) chances that you'll end up with a broken system are fairly low.

Btw let's get back to the point: in such cases you may end up with a disk which was filled up with obsolete kernels. The following snippets allows you to get all outdated kernels which are not in use, so you can automagically pipe its output to an apt-get remove -y in a cron job.

That may sound trivial, but what happens if you're not careful (e.g. if you try deleting all kernels but the latest) is that you might try removing the currently running kernel - and it's pretty bad if that happens in an unattended cron job.

WARNING: recent changes to the way Ubuntu marks dependencies and provided names for kernel headers require that you uncomment a couple of lines in the script towards the end; just remove the # at the beginning of the lines 46 and 47.

UPDATE: in recent Ubuntu versions, just invoking apt-get autoremove --purge will do the trick. Such command will remove all automatically installed packages that are no longer required in the running system. It can remove other packages beyond outdated kernels, by the way.