Skip to content

Instantly share code, notes, and snippets.

@beezly
Last active December 24, 2015 13:59
Show Gist options
  • Save beezly/6809337 to your computer and use it in GitHub Desktop.
Save beezly/6809337 to your computer and use it in GitHub Desktop.
Ubuntu machine keeps getting filled up with old kernels? Why not run this script from your crontab. === Warning - may trash your machine. Don't blame me. You downloaded it. === Run at any time without downloading (so long as you have wget) with wget -O - https://gist.github.com/beezly/6809337/raw | /bin/bash
#!/bin/bash
read -a kernels_installed <<< `dpkg -l 'linux-image-[0-9]*' | grep ^ii | awk '{ print $2 }'`
kernel_links=(/vmlinuz /vmlinuz.old)
kernels_to_keep=( )
DEBUG=0
for i in ${kernel_links[@]}; do
if [ $DEBUG -eq 1 ]; then echo "Checking $i"; fi
real_kernel_link=`readlink $i`
if [ $DEBUG -eq 1 ]; then echo "$i points to /$real_kernel_link"; fi
if [ $? -ne 0 ]; then
# we didn't find a kernel - bail - we want both
exit 1
fi
# Get the package this came from
dpkg_search=`dpkg -S /$real_kernel_link`
if [ $DEBUG -eq 1 ]; then echo "$real_kernel_link found: $dpkg_search"; fi
if [ $? -ne 0 ]; then
# Couldn't find a package? Bail
exit 1
fi
# We want just the package name
dpkg_name=`echo "$dpkg_search" | cut -d: -f 1`
# and we add it to the list
kernels_to_keep+=($dpkg_name)
done
# Bonus feature - won't delete current kernel
current_kernel_version=`uname -r`
kernels_to_keep+=("linux-image-$current_kernel_version")
if [ $DEBUG -eq 1 ]; then echo "Keeping: ${kernels_to_keep[@]}"; fi
kernels_to_delete=(${kernels_installed[@]})
# Remove the kernels we want to keep from the list
for i in ${kernels_to_keep[@]}; do
kernels_to_delete=(${kernels_to_delete[@]##$i})
done
if [ $DEBUG -eq 1 ]; then echo "Found: ${kernels_installed[@]}"; fi
if [ $DEBUG -eq 1 ]; then echo "Deleting: ${kernels_to_delete[@]}"; fi
if [ $DEBUG -eq 1 ]; then
dry_run="-s"
else
dry_run=""
fi
# Here goes... good luck.
apt-get -y $dry_run remove ${kernels_to_delete[@]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment