-
-
Save jpaulickcz/721ad60ad28bb7875a5689defe005305 to your computer and use it in GitHub Desktop.
Clean up old linux kernels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Run this script without any param for a dry run | |
# Run the script with root and with exec param for removing old kernels after checking | |
# the list printed in the dry run | |
# bash <(curl -Ls "https://gist.github.com/jpaulickcz/721ad60ad28bb7875a5689defe005305/raw/?clean-kernels-$(date +%s)") | |
# Function to get disk usage in MB | |
get_disk_usage() { | |
df --output=used / | tail -n 1 | awk '{print int($1/1024)}' | |
} | |
# Check for old kernels not in use | |
check_old_kernels() { | |
local in_use_kernel=$(uname -r) | |
local old_kernels=($(dpkg --list | grep -E 'linux-image-[0-9]+|linux-headers-[0-9]+|linux-modules-[0-9]+' | grep -v "$in_use_kernel" | awk '{print $2}')) | |
local old_kernel_count=${#old_kernels[@]} | |
if [ "$old_kernel_count" -eq 0 ]; then | |
echo -e "\e[32m[OK] There are no old kernels on the system.\e[0m" | |
else | |
local old_kernels_size=$(dpkg-query -W -f='${Installed-Size}\t${Package}\n' "${old_kernels[@]}" | awk '{total += $1} END {print total / 1024}') | |
echo -e "\e[33m[INFO] There are $old_kernel_count old kernels, taking up approximately $old_kernels_size MB.\e[0m" | |
fi | |
} | |
# Display kernel version | |
uname -a | |
IN_USE=$(uname -a | awk '{ print $3 }') | |
echo "Your in use kernel is $IN_USE" | |
# Find old kernels and calculate expected freed space | |
check_old_kernels | |
# Check disk space before cleanup | |
DISK_USAGE_BEFORE=$(get_disk_usage) | |
if [ "$1" == "exec" ]; then | |
for PACKAGE in $OLD_KERNELS; do | |
yes | apt purge "$PACKAGE" | |
done | |
apt autoremove -y | |
# Check disk space after cleanup | |
DISK_USAGE_AFTER=$(get_disk_usage) | |
# Calculate and display the freed space | |
SPACE_FREED=$(($DISK_USAGE_BEFORE - $DISK_USAGE_AFTER)) | |
# Display comparison with expected freed space | |
echo -e "\e[34m[INFO] Expected to free up approximately $old_kernels_size MB, actually freed $SPACE_FREED MB.\e[0m" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment