Wednesday, November 13, 2019

Bash one-liner to delete only old kernels

I've seen lots of threads on how to free space on the /boot partition and that is my objective as well. However, I'm only interested in deleting old kernels and not each one of them but the current one.



I need the solution to be a one-liner since I'll be running the script from Puppet and I don't want to have extra files lying around. So far I got the following:




dpkg -l linux-* | awk '/^ii/{print $2}' | egrep [0-9] | sort -t- -k3,4 --version-sort -r | sed -e "1,/$(uname -r | cut -f1,2 -d"-")/d" | grep -v -e `uname -r | cut -f1,2 -d"-"` | xargs sudo apt-get -y purge


To be more precise, what it does at the moment is the following:




  • List all the linux-* packages and print their names.

  • Only list the ones that have numbers and sort them, returning the reverse result. This way, older kernels are listed last.

  • Print only the results that go after the current kernel

  • Since there are some linux-{image,headers} results, make sure I won't purge anything related to my current kernel


  • Call apt to purge



This works, but I'm sure the solution can be more elegant and that it's safe for a production environment, since at least 20 of our servers run Ubuntu.



Thanks for your time,
Alejandro.

No comments:

Post a Comment

11.10 - Can't boot from USB after installing Ubuntu

I bought a Samsung series 5 notebook and a very strange thing happened: I installed Ubuntu 11.10 from a usb pen drive but when I restarted (...