Auto remove all old kernels in Ubuntu

By regularly installing updates you are ensuring that your computer is protected from known vulnerabilities and is working as intended. You also receive all the latest software versions, even the kernel which is the core of the operating system. In time, you’ll see multiple versions of it in the GRUB menu and it can possibly fill your root partition which in turn can lead to a variety of problems.


There are various ways to remove unused kernels, but the simplest one seems to be entering this line into the terminal:

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

If you want to play safe, you can use the following command:

sudo apt autoremove --purge

This command will remove all unused packages, including unused kernels. However it will keep the original kernel your distribution was shipped with and will also keep the second-newest installed kernel, so you’ll have fallbacks.