Purging old Linux Kernels

In Debian based derivatives, such as Ubuntu, Mint, Zorin, and other distros that use the “apt-get” package manager, I’ve noticed that sometimes old Linux Kernels pile up and start taking up more and more space. So I began looking for a fix and I found a forum post from a user named Jarno.

I wrote this script that removes “linux-*” packages that have lesser version than the currently booted one. I think it is not necessary to test package status. The command asks for confirmation before purging packages. If you don’t want that, add -y option to the apt-get command.

If you’re someone who intentionally boots multiple kernel versions, this probably isn’t for you. But for your ‘average’ user, the bash script / command they wrote follows:

sudo apt-get purge $(dpkg-query -W -f'${Package}\n' 'linux-' | sed -nr 's/.-([0-9]+(.[0-9]+){2}-[^-]+).*/\1 &/p' | linux-version sort | awk '($1==c){exit} {print $2}' c=$(uname -r | cut -f1,2 -d-))

Jarno continued:

However, to be able to leave configurable amount of spare kernels, I recommend to use my linux-purge script with –keep option. See here for more information about the script.

Despite the fact that the original post was from May 7, 2015 at 9:44 and was edited Sep 23, 2019 at 9:29, I have used the same commands in late 2025 in Ubuntu 24.04 and still found it successful at freeing up some space. It’s a useful tip to hang on to – but please, use at your own risk.