Remove old kernels automatically

E-Neutrino e-neutrino at web.de
Sun Oct 26 08:35:04 UTC 2014


Am 15.10.14 um 16:23 schrieb Tom H:
> On Wed, Oct 15, 2014 at 1:44 AM, Tom H <tomh0665 at gmail.com> wrote:
>> On Mon, Oct 13, 2014 at 8:59 AM, Andrew Langhorn <andrew at ajlanghorn.com> wrote:
>>>
>>> Using sed, uname and apt, I am trying to ensure that all kernels older than
>>> the current and one behind are uninstalled from my machines. I keep the
>>> current one, for obvious reasons, and the previous kernel in case I need to
>>> roll back.
>>>
>>> To do this, I'm using `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`, which pipes the output of `uname -r ` to sed,
>>> ignores any lines beginning with `ii` to ensure installed kernels aren't
>>> removed, and applies that to the ouput of `dpkg -l 'linux-*`.
>>>
>>> This ensures that all previous kernels present are removed.
>>>
>>> Can I blacklist the previous one, given that I don't know the name, as it
>>> may well change?
>>
>> Your sed command is painful to read! :)
>>
>> The kernel package corresponding to the currently-loaded kernel is
>> "linux-image-$(uname -r)".
>>
>> You can list the installed kernels with "ls -1t /boot/vmlinuz*" and
>> list the corresponding packages with "ls -t /boot/vmlinuz-* | cut
>> -d'-' -f2,3,4 | awk '{print "linux-image-"$0}'". Assuming that you're
>> booted using the latest kernel, you can exclude the first two from
>> your purge.
> 
> "ls -t /boot/vmlinuz-* | cut -d'-' -f2- | awk '{print
> "linux-image-"$0}'" is better in case there are more than 4 fields in
> the vmlinuz name.
> 

  Very nice tip!

  Here another enhancement, which excludes the currently running one
  and skips a configurable number of most-recent kernels:

  ls -t /boot/vmlinuz-* | cut -d'-' -f2- | current=$(uname -r) awk
'BEGIN {skip=1;}; {if (skip-- <= 0 && $0 != ENVIRON["current"]) print
"linux-image-"$0;}

  Note that this is not perfect in the sense that it will keep "skip"
  kernels or "skip+1" kernels, depending on whether the running kernel
  is one of the "skip" most recent kernels or not.

  ls -t /boot/vmlinuz-* | cut -d'-' -f2- | grep -v -e "$(uname -r)" |
awk 'BEGIN {skip=1;}; {if (skip-- <= 0) print "linux-image-"$0;}

  will keep the running kernel plus "skip" most recent kernels not
  counting the running one.





More information about the ubuntu-users mailing list