apt-remove-old-kernels 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env ruby
  2. # this script will detect all installed kernels and headers on a debian-based system
  3. # and give the option to remove all but the current set
  4. HEADERS_REGEX = '^linux-headers-'
  5. KERNEL_REGEX = '^linux-image-'
  6. UNAME_CMD = "uname -r"
  7. APT_SEARCH_CMD = "apt search"
  8. GREP_INSTALLED_CMD = "2> /dev/null | grep installed"
  9. GREP_DEFAULT_CMD = "cat /boot/grub/grub.cfg | grep 'set default'"
  10. GREP_ENTRIES_CMD = "cat /boot/grub/grub.cfg | grep 'menuentry ' | grep -v 'gnulinux-simple-'" # exclude group entries
  11. APT_REMOVE_CMD = "sudo apt-get remove"
  12. # helpers
  13. def print_default_grub_entry
  14. default_entry = `#{GREP_DEFAULT_CMD}`.split("\"")[1].to_i
  15. entries = `#{GREP_ENTRIES_CMD}`.split "\n"
  16. current_entry = entries[default_entry].split(/['"]/)[1]
  17. print "current default grub entry:\n\t" + current_entry + "\n\n"
  18. end
  19. # show current kernel
  20. current_release = `#{UNAME_CMD}`.strip
  21. current_kernel_version = current_release.split('-')[0..-2].join('-')
  22. print "\ncurrent running kernel:\n\t" + current_release + "\n"
  23. print "current kernel version:\n\t" + current_kernel_version + "\n\n"
  24. # show list of installed kernels
  25. installed_packages = `#{APT_SEARCH_CMD} #{HEADERS_REGEX} #{GREP_INSTALLED_CMD}`.split("\n")
  26. installed_packages += `#{APT_SEARCH_CMD} #{KERNEL_REGEX } #{GREP_INSTALLED_CMD}`.split("\n")
  27. print "installed packages (* indicates current):\n"
  28. installed_packages.map! do | ea |
  29. ea = ea.split(' ')[0].split('/')[0]
  30. print "\t" + ((ea.end_with? current_release) ? "* " : " ") + ea + "\n"
  31. ea
  32. end
  33. print "\n"
  34. # show list of older kernels to be removed
  35. remove_packages = installed_packages.select do | ea |
  36. (not ea.include? current_kernel_version) && (ea.split '-')[2].to_i > 0
  37. end
  38. print "packages to remove =\n\t" + ((remove_packages.size.zero?)? "none" : remove_packages.join("\n\t")) + "\n\n"
  39. # show current default grub entry
  40. print_default_grub_entry
  41. # run apt
  42. if remove_packages.empty?
  43. print "no older kernels installed" + "\n\n"
  44. else
  45. print "remove these " + remove_packages.size.to_s + " packages ?" + "\n\n"
  46. system APT_REMOVE_CMD + " " + remove_packages.join(" ")
  47. end
  48. # show current default grub entry
  49. print_default_grub_entry