One-liner to free up space from old kernels

As you upgrade your kernel, the old ones accumulate a bit of space in /boot.

To remove them and regain some space, here's a handy command:

sudo apt-get remove --purge $(dpkg -l 'linux-image-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d')

Does the trick all the time, especially for a dedicated but small /boot partition. :wink: It could possibly free up hundreds of MBs.

:warning: Always take caution removing old kernels, in case you need to boot with an older one. Double check the packages being removed are actually kernel packages. I've not had a problem with the command above.

For reference, here's some discussion about this command.


Thanks, it seems to work just fine. I usually use apt-get autoremove and delete the packages that it ignores manually (linux-headers) from time to time. This one removes all of them, although it is nice to keep an extra one just in case, which autoremove does.

Would this work for 20.04? I just executed the command, seemed to work, but noticed 42 directories full of files left behind in /lib/modules.

Still works, though it seems uninstalling the package tried to run rmdir but failed because the directories were not empty.

It's safe to remove old ones from /lib/modules except the one for the running (or latest?) kernel:

uname -r 

Just tried in a 20.04 VM, no breakage :slight_smile:

1 Like