Skip to content

Instantly share code, notes, and snippets.

@seveas
Last active January 5, 2021 19:23
Show Gist options
  • Save seveas/81ea422aef6689a909c3348c783e37bf to your computer and use it in GitHub Desktop.
Save seveas/81ea422aef6689a909c3348c783e37bf to your computer and use it in GitHub Desktop.
#!/bin/bash
if [ "$1" == "--noop" ]; then
NOOP=1
VERBOSE=1
fi
# We only support stretch or newer
if [ "$(lsb_release -cs)" == "jessie" ]; then
exit 0
fi
if [ "$(lsb_release -cs)" == "precise" ]; then
exit 0
fi
# We want to run under the github apt lock so we don't interfere with unattended-upgrades, puppet and heaven
if [ "$LOCKED" != 'yes' ]; then
export LOCKED=yes
exec /usr/local/sbin/gh-apt-lock "$0" "$@"
fi
arch=$(dpkg --print-architecture)
running=$(uname -r)
running=${running%-$arch}
# sort -V gives us the newest, the seds strip off the package name
newest=$(dpkg-query -W -f '${db:Status-Want}\t${Package}\t${Version}\n' 'linux-image*' | grep ^install | sort -k3 -V | tail -n1 | cut -f2)
newest=${newest#linux-image-}
newest=${newest%-$arch}
if [ -n "$VERBOSE" ]; then
echo "Removing everything except $running and $newest"
fi
toremove=$(dpkg-query -W -f '${Package}\n' 'linux-image-[0-9]*' 'linux-headers-[0-9]*' | grep -v "$running" | grep -v "$newest")
if [ -n "$toremove" ]; then
if [ -n "$VERBOSE" ]; then
echo Removing $toremove
fi
if [ -z "$NOOP" ]; then
apt-get -y remove --purge $toremove
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment