Skip to main content

Raymii.org Raymii.org Logo

Quis custodiet ipsos custodes?
Home | About | All pages | Cluster Status | RSS Feed

Remove unused Ubuntu kernels

Published: 28-10-2013 | Author: Remy van Elst | Text only version of this article


❗ This post is over ten years old. It may no longer be up to date. Opinions may have changed.

This one liner will help you remove unused Ubuntu kernels. Ubuntu does not remove kernels when they install a new one, however the default /boot partition is relatively small, about 100MB. So after 10 kernels, you can get No Space Left On Device errors with apt-get upgrading. Then you can eitehr remove them manually, or use this one liner to automatically remove them all.

export KERNEL="$(uname -r | grep -Po '([0-9\.\-]*[0-9])?')"; dpkg --get-selections | grep -E "linux-(header|image).*" | grep -iw install | sort | grep -v "$KERNEL" | grep -v "lts" | sed 's/install//g' | xargs dpkg -P

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $100 credit for 60 days.

Here's the command by command explanation:

export KERNEL="$(uname -r | grep -Po '([0-9\.\-]*[0-9])?')"

The first portion sets the current kernel number in a variable KERNEL. It only takes the number, and greps out any additions like -generic or -server.

dpkg --get-selections 

The second portion first prints out all available packages.

grep -E "linux-(header|image).*"

The third portion greps for all packages with either linux-header or linux- image in the name.

grep -iw install

The fourth portion greps out only installed packages.

sort

The fifth portion sorts the output.

grep -v "$KERNEL" | grep -v "lts"

The sixth portion filters out the current kernel and the lts kernel package. Removing those will cause problems.

sed 's/install//g'

The seventh part strips off the install part.

xargs dpkg -P

The last part actually removes the packages. xargs send all the package names to dpkg. Then dpkg -P purges the packages. That means, removing them and removing their configs.

Tags: apt-get , bash , grep , kernel , sed , snippets , ubuntu