Removing Old Kernels

Mostly, I don’t worry about the accumulation of old kernels building up in /boot and sudo apt-get autoremove may scrub most of them, but sometimes it doesn’t when I’m doing something else and I must wade through the accumulation of old packages in Synaptic. Removing all those packages by hand gets tedious, but I’m reluctant to unleash a rarely used script on the clutter for fear of creating a worse problem.

The iterator in this burst of Bash line noise:

for f in $(ls /boot | grep vmlinuz | cut -d\- -f2,3 | sort | head -n -1) ; do dpkg -l | grep "^ii\ \ linux-" | grep $f | cut -d" " -f 3 >> /tmp/pkgs.txt ; done

… parses the list of kernels in /boot into version numbers, finds the corresponding installed packages, sorts them in ascending order, discards the last entry so as to not uninstall the most recent kernel, and passes each line of the resulting list into the loop.

N.B: The grep argument has two spaces after the ii that WordPress would destroy without the escaping backslashes. You can try "^ii linux-", but if the loop puts nothing in the file, that’s why.

Given each kernel version number, the loop extracts the package names from the installed kernel packages and glues the result onto a file that looks like this:

cat /tmp/pkgs.txt

Convert that file into a one-line string of package names and verify what would happen:

paste -s -d " " /tmp/pkgs.txt | xargs sudo apt-get --dry-run purge

If everything looks good, change --dry-run to --yes and blow ’em away.

No, I can’t possibly remember or type that gibberish by hand, but I do know where to find it…

2 thoughts on “Removing Old Kernels

  1. Sometimes those old kernels can add up to many gigabytes, leading to a lack of space when you want to upgrade or some such. Incidentally, the new, unified, easier to use apt command can also list installed packages with $ apt list --installed linux-*. The advantage being that you can actually remember this command (whereas I almost always have to look up how to use dpkg), although it’s not really any better or worse than going into Synaptic without the subsequent filtering you posted.

    1. That list includes a bunch of stuff after the package name, but eliminating that noise looks easier than the hideous loop I pieced together.

      Ya learn something new every day around here: thanks!

Comments are closed.