I made a cli version for this, had it a long time ago, for Ubuntu, recently made a version which supports Debian/Ubuntu and has been tested on:
- Ubuntu 8.04 LTS / 10.10
- Debian stable / testing / unstable
The rmkernel function below will remove all kernels, kernel header, kernel modules and backport packages except for the running kernel. The function will make sure that any kernel package related to your current kernel will stay installed. As said, all others will be removed. The script depends on aptitude, so for those who haven't installed that package yet: sudo apt-get install aptitude
Regular warnings apply:
- Use this only when your current kernel is working as expected, since we do remove all kernels and kernel modules for kernels which we are not running.
- This script will not work in a chrooted environment.
Include these functions in your .bashrc/.zshrc:
Code:
_egrep-pattern () {
[ -z "$1" ] && return
local regexp=$1
shift
for i in $*
do
regexp="$regexp|$i"
done
echo ${regexp}
}
rmkernel () {
local cur_kernel="$(uname -r)"
local all_kernels="$(dpkg -l | grep -- linux- | egrep -- "-(image|headers|backports|modules|firmware)" \
| grep "^ii" | awk '{print $2}')"
local cur_kernel_pkgs="$(echo -e "$all_kernels" | grep "$cur_kernel$")"
local cur_kernel_img=$(echo -e "$cur_kernel_pkgs" | grep image)
local cur_kernel_hdr=$(echo -e "$cur_kernel_pkgs" | grep headers)
if [ -z "$cur_kernel_img" ]
then
echo "Unable to get the current kernel package. What are you doing?" >&2
echo "Possibly running in a chroot, eitherway aborting!" >&2
return 1
fi
local cur_kernel_img_rdepends="$(apt-cache rdepends $cur_kernel_img | tail -n +3)"
local cur_kernel_hdr_rdepends
local cur_kernel_hdr_depends
if [ -n "$cur_kernel_hdr" ]
then
cur_kernel_hdr_rdepends="$(apt-cache rdepends $cur_kernel_hdr | tail -n +3)"
cur_kernel_hdr_depends="$(apt-cache depends $cur_kernel_hdr | egrep 'linux-(image|headers)' | grep Depends | awk '{print $2}')"
fi
local keep="$(_egrep-pattern $cur_kernel_pkgs $cur_kernel_img_rdepends $cur_kernel_hdr_rdepends $cur_kernel_hdr_depends)"
if [ -z "$keep" ]
then
echo "Unable to determine which kernels to keep!" >&2
echo "This should not happen in normal circumstances" >&2
return 1
fi
local remove="$(echo -e "$all_kernels" | egrep -v "^($keep)$")"
local rm_modules="$(find /lib/modules -mindepth 1 -maxdepth 1 -type d ! -name ${cur_kernel} )"
if [ -n "$remove" ] || [ -n "$rm_modules" ]
then
echo "Going to remove the following kernel packages:" $remove
echo "Going to remove the following kernel modules directories afterwards:" $rm_modules
echo "Waiting 5 seconds for ctrl-c to abort mission"
sleep 3
echo -n ..2
sleep 1
echo -n ..1
sleep 1
echo "..Start removal"
if [ -n "$remove" ]
then
sudo aptitude -y purge $remove
fi
[ -n "$rm_modules" ] && sudo rm -rf $rm_modules
fi
return 0
}
Source your .bashrc/.zshrc.
Now run rmkernel from your shell and you will remove all unneeded kernel packages. Enjoy!
Bookmarks