Skip to content

Instantly share code, notes, and snippets.

@bartman
Created February 11, 2021 13:26
Show Gist options
  • Save bartman/7cd6c515d90a87d44ee23ca112ddb2bd to your computer and use it in GitHub Desktop.
Save bartman/7cd6c515d90a87d44ee23ca112ddb2bd to your computer and use it in GitHub Desktop.
cleanup-boot
#!/bin/bash
# this script will remove any stale kernel- and kernel-headers- packages
# it will keep the current (uname -r) and latest kernel package and its headers
SUDO=sudo
while [ -n "$1" ] ; do
case "$1" in
-h) echo "${0##*/} [ -h ] [ -n ]" ; exit 0 ;;
-n) SUDO=echo ;;
*) echo >&2 "unknown option $1"; exit 1 ;;
esac
shift
done
current="`uname -r`"
current="${current%-*}"
kernels=( $( dpkg -S /boot/vmlinuz-* | cut -d : -f 1 | sort -V ) )
latest="${kernels[-1]}"
latest="${latest#linux-image-}"
latest="${latest%-*}"
headers=( $( dpkg -l linux-headers-[0-9]\* | awk '/^.i/ { print $2 }' | sort -V ) )
echo "# current: $current"
echo "# latest: $latest"
remove=()
for pkg in "${kernels[@]}" "${headers[@]}" ; do
[[ $pkg =~ $current ]] && { echo >&2 "# keeping $pkg (current)" ; continue ; }
[[ $pkg =~ $latest ]] && { echo >&2 "# keeping $pkg (latest)" ; continue ; }
remove+=( $pkg )
done
[ ${#remove[@]} = 0 ] && { echo >&2 "# nothing to remove" ; exit 0 ; }
$SUDO dpkg --remove ${remove[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment