Removing old kernel packages

Jonathan Marsden jmarsden at
Thu Mar 8 01:20:55 UTC 2012

Here is what I have used for a long time in Ubuntu to remove older
kernels and related packages...

alias oldkernels='dpkg -l linux-{headers,image}-[23]\* |grep ^ii |grep
-v $(uname -r |sed -e "s/-generic//") |cut -c 5-40'

This one just lists kernel-related packages, excluding those for the
currently running kernel, so you can look at the list and see what could
be removed.

alias remove-oldkernels='sudo apt-get remove $(dpkg -l
linux-{headers,image}-[23]\* |grep ^ii |grep -v $(uname -r |sed -e
"s/-generic//") |cut -c 5-40)'

This one removes everything listed by oldkernels.  Since there will be
headers, image, and image-VERSION-generic packages for any given kernel
package version, this command will prompt before actually removing
anything, so it is relatively safe.

function remove-oldkernels-except () { sudo apt-get remove $(dpkg -l
linux-{headers,image}-[23]\* |grep ^ii |grep -v $(uname -r |sed -e
"s/-generic//") |cut -c 5-40 | grep -v $1) ; }

This one is for folks who want to retain more than just the most recent
kernel.  It takes a single argument which is a regex and packages
matching the regex you supply are retained, as well as the most recent
kernel.  So you can do

  remove-oldkernels-except 2.6.32-35

and it will remove all kernel packages except that one *and* the
currently running kernel.  It prompts in the same way remove-oldkernels

I've used these for a long time without issues myself, and have
recommended them to a few friends.  I think they are more comprehensive
(they remove the headers packages as well as the kernel packages) and
easier to read than the sed extravaganza on the wiki page.  But maybe I
am just biased :)

This isn't really "code", in the sense of programming, it is just
everyday one-liner shell scripting.  I have these in my ~/.bashrc file.

  Jonathan Marsden
  jmarsden at

More information about the Lubuntu-users mailing list