Remove old kernels from debian based systems

I’ve always hated that there is no simple way to remove all the kernels you don’t use from the Debian/Ubuntu system.

But fortunately it’s really easy to do so, from the command line.

First thing reboot your system and start the kernel you want to keep, in this instance I want to keep the newest only, because I’m dual-booting between Windows and Ubuntu, I just keep only the latest kernel.

So to do that we just write in the console, you can also use purge instead of remove.

dpkg -l linux-* | awk '/^ii/{ print $2}' | grep -v -e `uname -r | cut -f1,2 -d"-"` | grep -e [0-9] | xargs sudo apt-get -y remove

Or:

dpkg -l linux-* | awk '/^ii/{ print $2}' | grep -v -e `uname -r | cut -f1,2 -d"-"` | grep -e [0-9] | xargs sudo apt-get -y purge

So maybe I should explain what is happening here, though if you have used linux you know most if not all of these commands.

awk - used for textual data manipulation.

grep - filters out the data from the input

cut - remove sections from each line of files

uname - shows system information

dpkg - package manager in debian distributions

xargs - build and execute command lines from standard input

So basically I use dpkg to get  the linux kernel files, and we pipe it to awk to filter out everything but the package name, and we use uname and cut to get the kernel version only, and when we put it together we select all linux kernel files except the one provided by uname .

And that is it, the best way to learn it is to try and experiment by yourself.