Run an Ubuntu system long enough, and you’ll eventually have a large number of kernels installed. These don’t cause any harm, but they do take up disk space and appear in the GRUB menu at boot. So every now and again, I take a moment and purge the old kernels.
When you have just one system, this is easy. Just list all packages with dpkg -l or a graphical manager like Synaptic, and mark the old ones for removal.
But there are some gotchas. Don’t remove the currently-running kernel. It would be bad. Also don’t remove the latest kernel. That’s the one you want to be running.
So when cleaning up, you must carefully pick all the kernels, modules, and headers you want to purge. It is tiresome to do this by hand more than once. So I wrote a bash macro to do it for me. Just paste this into the shell:
( \
KERNEL_HIGHEST=$(dpkg -l 'linux-image-[0-9.]*-[0-9]*-[a-zA-Z0-9]*' | grep ^ii | awk '{print $2}' | sort -V | tail -n 1 | sed 's/^linux-image-\([0-9.]*-[0-9]*\)-.*$/\1/') ; \
KERNEL_CURRENT=$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/") ; \
sudo apt-get purge $(dpkg -l 'linux-*-[0-9-]*' | grep ^ii | awk '{print $2}' | sed "/$KERNEL_CURRENT/d;/$KERNEL_HIGHEST/d" ) ; \
)
This code does the following:
- Find the version of the newest (highest-numbered) kernel
- Find the version of the currently-running kernel
- List all kernel images, modules, and headers
- Exclude everything matching the newest or current kernel versions
- Use apt-get to purge all the rest
Update 2012-09-06: The code to find KERNEL_HIGHEST was wrong. It gave incorrect results when version numbers increase in order of magnitude (such as from 3.2.0-9 to 3.2.0-10), and had problems with beta kernels (such as linux-image-3.3.0-030300rc2-generic). This could cause one old kernel to be retained, or the newest kernel to be removed, as long as it wasn’t the running kernel. The bug is now fixed. Thanks to Dean Henrichsmeyer at Canonical for providing feedback.
Update 2012-11-29: The above command only works on Ubuntu 10.04 and later. Prior to this release, sort is missing the -V switch to sort by version number.
Leave a Reply