If you are like me, you will have noticed on Ubuntu (and sometimes Debian) that stale old kernels remain on the disk even when they aren’t needed anymore. I wrote a little Bash function to get rid of those kernels.
You can find the respective function here as well. This one will actually get updated if issues are found with the script. Simply source the script with
. prune-kernels or
source prune-kernels and then call the function.
So what does this piece of code do? Well, it uses the
/vmlinuz.old symlinks to figure out the newest kernel and the one prior to that. Those two are skipped when pruning stale kernels. In addition it uses
uname -r to find out which kernel is currently running and skips it as well. It is pretty verbose in showing what’s going on and which of the kernels have been skipped.
Then it calls
apt-get remove on the list of stale kernels to remove them. If you choose no when
apt-get remove prompts you, any further action will be skipped. If there are no stale kernels to remove, the function will make this clear.
apt-get remove ran (and returned a success exit code), the function will collect all the file names from the
/boot folder belonging to the previously removed kernels, if any, and unlinks them.
If you don’t run the function as root, the function is going to call the
rm commands through
sudo. This means you will be prompted for your password twice at worst.
You may choose to give
--old as a command line option to the
prune-kernels function in order to make it also prune the previous kernel (pointed to by
/vmlinux.old). By default it will skip this one.
Safer implementation of pruning of old kernels on Debian and Ubuntu that will skip (by default) the running kernel, kernel referenced by
/vmlinuz and by