How to easily remove old kernels in Ubuntu 20.04 LTS?
I have old Linux kernel versions that I don't use so I was trying to remove them.
List of installed kernels from dpkg --list | grep linux-image
linux-image-5.4.0-26-generic (5.4.0-26.30)
linux-image-5.4.0-33-generic (5.4.0-33.37)
linux-image-5.4.0-37-generic (5.4.0-37.41)
Solution 1:
Here are the steps to remove unused kernels.
Check what current kernel You run:
uname -a
Linux blackhole 5.6.13-050613-lowlatency #202005141310 SMP PREEMPT Thu May 14 13:17:41 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
I am running 5.6.13-050613-lowlatency
List all installed kernels in Your OS:
dpkg --list | egrep -i --color 'linux-image|linux-headers|linux-modules' | awk '{ print $2 }'
linux-headers-5.6.11-050611
linux-headers-5.6.11-050611-lowlatency
linux-headers-5.6.13-050613
linux-headers-5.6.13-050613-lowlatency
linux-image-unsigned-5.6.11-050611-lowlatency
linux-image-unsigned-5.6.13-050613-lowlatency
linux-modules-5.6.11-050611-lowlatency
linux-modules-5.6.13-050613-lowlatency
Uninstall kernels You don't need:
sudo apt purge linux-headers-5.6.11-050611 linux-headers-5.6.11-050611-lowlatency linux-image-unsigned-5.6.11-050611-lowlatency linux-modules-5.6.11-050611-lowlatency
Solution 2:
You can try out this script
remove_old_kernels.sh
#!/bin/bash
# Run this script without any param for a dry run
# Run the script with root and with exec param for removing old kernels after checking
# the list printed in the dry run
uname -a
IN_USE=$(uname -a | awk '{ print $3 }')
echo "Your in use kernel is $IN_USE"
OLD_KERNELS=$(
dpkg --list |
grep -v "$IN_USE" |
grep -Ei 'linux-image|linux-headers|linux-modules' |
awk '{ print $2 }'
)
echo "Old Kernels to be removed:"
echo "$OLD_KERNELS"
if [ "$1" == "exec" ]; then
for PACKAGE in $OLD_KERNELS; do
yes | apt purge "$PACKAGE"
done
fi
Run it like this for a dry run:
remove_old_kernels.sh
If all looks good, run it again like this:
sudo remove_old_kernels.sh exec
Solution 3:
Just use this:
sudo apt-get autoremove --purge