Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env bash
- #
- # 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)
- # Author: Peter Maloney
- args=()
- if [ "$1" = "-n" -o "$1" = "--dry-run" -o "$1" = "-s" -o "$1" = "--simulate" ]; then
- # dry run
- args=(--dry-run)
- else
- args=(-y)
- fi
- # takes one arg with space separated numbers, eg. version 4.3-1 is sent here as "4 3" and a second call takes "1"
- # 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)
- pad() {
- IFS=' '
- local lpad=
- for n in $1; do
- lpad="${lpad}$(printf "%010d" "$n")"
- done
- local rpad="$lpad"
- while [ "${#rpad}" -lt 50 ]; do
- rpad="${rpad}0"
- done
- echo -n "$rpad"
- }
- # sorts by version, trying to handle all the dotted and hyphenated numbers
- version_sort() {
- IFS=$'\n'
- for line in $(cat); do
- local base_split=$(awk -F'-' '{print $1}' <<< "$line" | sed -r 's|[^0-9a-zA-Z]| |g')
- local distro_split=$(awk -F'-' '{print $2}' <<< "$line" | sed -r 's|[^0-9a-zA-Z]| |g')
- local base_padded=$(pad "$base_split")
- local distro_padded=$(pad "$distro_split")
- echo "$line $base_padded $distro_padded"
- done | sort -t' ' -k2,2n -k3,3n | cut -d' ' -f1
- }
- current=$(uname -r | grep -Eo "[0-9][0-9\.-]+[0-9]")
- autoremove() {
- name="$1"
- latest=$(dpkg -l "${name}*" | awk '$1=="ii" {print $2}' | grep -Eo "[0-9][0-9\.-]+[0-9]" | version_sort | tail -n1)
- # remove all except the currently booted one, and the latest one
- apt-get purge "${args[@]}" $(dpkg -l "${name}*" | grep -E "${name}-[0-9\.-]+" | awk '$1 == "ii" || $1 == "rc" {print $2}' | grep -vE "$current|$latest")
- }
- # debian/ubuntu kernels
- autoremove "linux-image"
- autoremove "linux-headers"
- autoremove "linux-image-extra"
- # proxmox PVE kernels
- autoremove "pve-kernel"
- autoremove "pve-headers"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement