#!/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[@]}