Skip to content

Instantly share code, notes, and snippets.

@zoonderkins
Last active December 11, 2023 05:04
Show Gist options
  • Save zoonderkins/f87979a802669934839481b9d2182ce5 to your computer and use it in GitHub Desktop.
Save zoonderkins/f87979a802669934839481b9d2182ce5 to your computer and use it in GitHub Desktop.
remove-old-kernel-linux.sh

Usage

chmod +x ./remove-old-kernel-linux.sh

./remove-old-kernel-linux.sh exec
#!/bin/bash -e
# Run this script without any arguments for a dry run
# Run the script with root and with exec arguments for removing old kernels and modules after checking
# the list printed in the dry run
# Source: https://askubuntu.com/a/1409370
uname -a
IN_USE=$(uname -a | awk '{ print $3 }')
echo "Your in use kernel is $IN_USE"
OLD_KERNELS=$(
dpkg --get-selections |
grep -v "linux-headers-generic" |
grep -v "linux-image-generic" |
grep -v "linux-image-generic" |
grep -v "${IN_USE%%-generic}" |
grep -Ei 'linux-image|linux-headers|linux-modules' |
awk '{ print $1 }'
)
echo "Old Kernels to be removed:"
echo "$OLD_KERNELS"
OLD_MODULES=$(
ls /lib/modules |
grep -v "${IN_USE%%-generic}" |
grep -v "${IN_USE}"
)
echo "Old Modules to be removed:"
echo "$OLD_MODULES"
if [ "$1" == "exec" ]; then
apt-get purge $OLD_KERNELS
for module in $OLD_MODULES ; do
rm -rf /lib/modules/$module/
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment