You can use this one-liner to automatically clean up all old kernels (make sure to restart the computer before doing this if you have just updated the kernel):
sudo apt purge $( dpkg --list | grep -P -o "linux-(headers|image)-\d\S+" | grep -v $(uname -r | grep -P -o ".+\d") )
What it does is uninstall (apt purge
) the installed packages (dpkg --list
) whose names match "linux-headers-[number]" or "linux-image-[number]" (grep -P -o "linux-(headers|image)-\d\S+"
), except (grep -v
) those corresponding to the current kernel version (uname -r | grep -P -o ".+\d"
).
Sources:
- CommandLineFu.com - the original inspiration
- Ask Ubuntu - using apt’s "purge" rather than "remove")
- Ask Ubuntu - ensuring the entries returned could be safely removed
- Stack Overflow - using PCRE in
grep
(\d
,\S
, etc) and using the-P
option - Super User - using
-o
to makegrep
return only the matched content