Advertisement
peetaur

bc-kernel-cleanup

Sep 26th, 2016
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.16 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. #
  3. # Deletes all kernels except the currently booted one, and the newest. (Possibly not ideal if you want different types, like the lowlatency, and xen and generic all at the same time)
  4. # Author: Peter Maloney
  5.  
  6. args=()
  7. if [ "$1" = "-n" -o "$1" = "--dry-run" -o "$1" = "-s" -o "$1" = "--simulate" ]; then
  8.     # dry run
  9.     args=(--dry-run)
  10. else
  11.     args=(-y)
  12. fi
  13.  
  14. # takes one arg with space separated numbers, eg. version 4.3-1 is sent here as "4 3" and a second call takes "1"
  15. # left-0-pads each number into 10 digits, eg. 00000000040000000003 so length of the numbers doesn't matter for sorting, and then right-zero-pads that to 50 length so having more numbers doesn't make the version larger (until you exceed 5 numbers or 50 chars)
  16. pad() {
  17.     IFS=' '
  18.     local lpad=
  19.     for n in $1; do
  20.         lpad="${lpad}$(printf "%010d" "$n")"
  21.     done
  22.    
  23.     local rpad="$lpad"
  24.    
  25.     while [ "${#rpad}" -lt 50 ]; do
  26.         rpad="${rpad}0"
  27.     done
  28.     echo -n "$rpad"
  29. }
  30.  
  31. # sorts by version, trying to handle all the dotted and hyphenated numbers
  32. version_sort() {
  33.     IFS=$'\n'
  34.     for line in $(cat); do
  35.         local base_split=$(awk -F'-' '{print $1}' <<< "$line" | sed -r 's|[^0-9a-zA-Z]| |g')
  36.         local distro_split=$(awk -F'-' '{print $2}' <<< "$line" | sed -r 's|[^0-9a-zA-Z]| |g')
  37.        
  38.         local base_padded=$(pad "$base_split")
  39.         local distro_padded=$(pad "$distro_split")
  40.            
  41.         echo "$line $base_padded $distro_padded"
  42.     done | sort -t' ' -k2,2n -k3,3n | cut -d' ' -f1
  43. }
  44.  
  45. current=$(uname -r | grep -Eo "[0-9][0-9\.-]+[0-9]")
  46.  
  47. autoremove() {
  48.     name="$1"
  49.    
  50.     latest=$(dpkg -l "${name}*" | awk '$1=="ii" {print $2}' | grep -Eo "[0-9][0-9\.-]+[0-9]" | version_sort | tail -n1)
  51.  
  52.     # remove all except the currently booted one, and the latest one
  53.     apt-get purge "${args[@]}" $(dpkg -l "${name}*" | grep -E "${name}-[0-9\.-]+" | awk '$1 == "ii" || $1 == "rc" {print $2}' | grep -vE "$current|$latest")
  54. }
  55.  
  56. # debian/ubuntu kernels
  57. autoremove "linux-image"
  58. autoremove "linux-headers"
  59. autoremove "linux-image-extra"
  60. # proxmox PVE kernels
  61. autoremove "pve-kernel"
  62. autoremove "pve-headers"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement