Remove old Ubuntu- / Debian kernel images

#!/bin/bash
KEEP=2
CURRENT=$(uname -r)
KERNELCOUNT=$(dpkg -l linux-image-3* | grep ii | wc -l)
KERNELS=$(dpkg -l linux-image-3* | grep ii | cut -d' ' -f 3)
REMOVECOUNT=$((KERNELCOUNT-KEEP))
REMOVEKERNELS=$(dpkg -l linux-image-3* | grep -v $CURRENT | grep ii | cut -d' ' -f 3 | head -n $REMOVECOUNT)
if [ $REMOVECOUNT -le 0 ];
then
  echo "I was told to keep $KEEP kernel revisions (including current version), but only $KERNELCOUNT kernels are installed. Exiting now."
  exit 1
fi
echo "Currently running on kernel $CURRENT, found $KERNELCOUNT installed kernels:"
echo "$KERNELS"
echo "I was told to keep $KEEP kernel revisions (including current version), so i will remove $REMOVECOUNT old kernel packages."
echo
echo "About to purge kernel versions:"
echo $REMOVEKERNELS
echo
apt-get purge $REMOVEKERNELS

Make sure to be running the latest kernel image that is installed on your system! (also, use at your own risk)

Autor: emmjott

# whoami root